Authentication Feature Testing in GraphQL
Learn how to test the authentication features in the GraphQL application.
We'll cover the following...
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.
func graphQLHandler() *chi.Mux {// create a new router or handlervar handler *chi.Mux = NewGraphQLHandler()// connect to the test databaseerr := database.Connect(utils.GetValue("DATABASE_TEST_NAME"))// if connecting to the database failed, print out the errorif err != nil {log.Fatalf("Cannot connect to the test database: %v\n", err)}fmt.Println("Connected to the test database")// return the handlerreturn 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.
func getJWTToken(user model.User) string {// generate JWT tokentoken, err := utils.GenerateNewAccessToken(user.ID)// if token generation failed, return an errorif err != nil {panic(err)}// return the JWT token for the authorization headerreturn "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 ...