...

/

Authentication Feature Testing in GraphQL

Authentication Feature Testing in GraphQL

Learn how to test the authentication features in the GraphQL application.

Test the application

The testing database is already prepared for testing. To create a test, we add a file called server_test.go to the project’s root directory. After the file is created, we create a function called graphQLHandler() to return the handler for the GraphQL application.

Press + to interact
func graphQLHandler() *chi.Mux {
// create a new router or handler
var handler *chi.Mux = NewGraphQLHandler()
// connect to the test database
err := database.Connect(utils.GetValue("DATABASE_TEST_NAME"))
// if connecting to the database failed, print out the error
if err != nil {
log.Fatalf("Cannot connect to the test database: %v\n", err)
}
fmt.Println("Connected to the test database")
// return the handler
return handler
}

Below is an explanation of the code above:

  • In line 3, the application router is created with the NewGraphQLHandler() function.

  • In line 6, the testing database is connected with the Connect() function.

  • In line 16, the handler is returned.

Next, we create a function called getJWTToken() to generate a JWT token for testing features that require authentication, like creating a new blog.

Press + to interact
func getJWTToken(user model.User) string {
// generate JWT token
token, err := utils.GenerateNewAccessToken(user.ID)
// if token generation failed, return an error
if err != nil {
panic(err)
}
// return the JWT token for the authorization header
return "Bearer " + token
}

As seen in the code above, the JWT token is generated with GenerateNewAccessToken() with the ID of the user as a parameter. If the ...