Testing Queries and Mutations on GraphQL Server
In this article we will test GraphQL Query & Mutations using easy-graphql tool
Making some test of your code is always a good practice that you should implement. The tests that you do will help you prevent some bugs and also it will ensure that your app work as you think it should work.
Sometimes making tests can be difficult and will require a lot of code, but most of the times it depends on the implementation that you’re using to test your code; there are packages that can help you make the tests with a few lines of code.
Today I’m going to introduce easygraphql-tester which is a npm package that will help you test your Schema, Queries, and Mutations in the server side and also in the client side. Using easygraphql-tester doesn’t need a lot of extra code to test your Schema, Queries, and Mutations. If the query is success, it will return a mock of the fields that you requested. The tester also is going to validate the arguments in case the query is expecting some and the type of the argument.
Set the mutation as a const
Call test from tester pass as first argument if the test should pass, as second argument the mutation and as a third one the variables that the input are expecting
If the query is success, it will return a mock of the fields that you requested on the mutation.
Mocking Queries and Mutations:
Call the method .mock() and pass an object with this options:
query: It’ll be the query/mutation to test.
variables: This is required if it is a mutation, it must be an object with the fields of the input.
fixture: This is optional and it is if you want to pass your custom fixtures.
saveFixture: By default is false, if you pass fixtures, and set it to truewhen you make the same query again, it will return the fixture value.
The result will have top-level fields, it means that the result will be an object with a property that is going to be the name (top level field) of the query or alias with the mocked result.
If there is an error on the query or mutation easygraphql-tester will let you know what is happening. Trying to access an invalid field id on getMe -> father
Invalid arguments on query
To get better results on your test you can use it with Mocha & Chai (also you can use it with your favorite ones) to test the results and validate the fields that are returning.
Here is a demo that can be useful, check all the files to see the test cases, also, check the console to see the result of a mocked query.
If you like this package don’t forget to give a ⭐️ on GitHub