We will test the following GraphQL resolver which has authorization and permission checks in place. If the user isnât authenticated, the resolver returns an error. If the requirements for the database entity arenât met, the resolver returns an error. Otherwise, the resolver creates a new database entity.
If we would use a GraphQL resolver middleware â which is optional â, it can be simplified to the following:
Either way, letâs jump into testing this GraphQL resolver with Jest. We call the resolver function with all its arguments and expect to resolve its returned promise to true if all requirements are met:
If you need to mock the database request with Jest, check out this tutorial about Jest mocking . Once you mocked your database API, you could add more assertions to your test case:
Anyway, letâs keep the test case simple without the database assertions. So far, we have only tested the happy path of the resolver logic where we meet all the requirements. What about if the user isnât authenticated?
Normally, we would expect the promise to reject. However, in GraphQL we successfully return the error as resolved result. This way, we can also test the other conditional logic for the GraphQL resolver:
This is it. GraphQL resolvers are only functions in the end. You can import them in your test file, call the resolver, and perform assertions. By having authorization and permission resolvers in place, you can also test the unhappy path when something goes wrong. In the end, the GraphQL server returns a promise, whether it is a successful result or an error.