Posts Test gqlgen resolvers that rely on context values
Post
Cancel

Test gqlgen resolvers that rely on context values

The problem

You are using gqlgen for building GraphQL servers in your Go projects. But your queryResolver or mutationResolver rely on some context value. For example as you are using gin and add values to your request context with middlewares. Therefore you need a way to modify the context of the gqlgen client in your tests.

An example resolver code could look like the following.

1
2
3
4
5
6
7
func (r *mutationResolver) CreateCategory(ctx context.Context, title string) (*model.Category, error) {
    currentUser := ctx.Value("User").(db.User)

    // ...

    return result, nil
}

The solution

The following code shows you how to add values to context when testing gqlgen resolvers with the client.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Add param variables to context of client request
// The gqlgen client accepts functional options as the following one
func addContext(user db.User) client.Option {
    return func(bd *client.Request) {
        ctx = context.WithValue(ctx, "User", user)
        bd.HTTP = bd.HTTP.WithContext(ctx)
    }
}

// Example tests
func TestMutationResolver(t *testing.T) {
    // Create the gqlgen client for testing
    h := handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{Resolvers: &Resolver{}}))
    c := client.New(h)

    // Example test
    t.Run("Create category", func(t *testing.T) {
        // struct that saves the response of the mutation below
        var resp struct {
            CreateCategory struct{ Title string }
        }

        // Create the variable that is passed to addContext
        user := db.User{}

        // Call the resolver via the client and modify the context via functional options
        c.MustPost(`
            mutation($title: String!) {
                createCategory(title:$title) {
                    title
                }
            }`,
            &resp,
            client.Var("title", category.Title),
            addContext(user),
        )

        // an example assertion
        assert.Equal(t, "Awesome blogs", resp.CreateCategory.Title)
    })
}

References

This post is licensed under CC BY 4.0 by the author.