Steve Y.
Steve Y.

Reputation: 87

Unit Tests for GraphQL Node JS App

I developed a graphql node js app with custom resolvers. Can anyone point me to some documentation where it illustrates how to properly write unit tests for my service? Or if someone has done it before and can point me in the right direction that would be great!

Upvotes: 3

Views: 5184

Answers (2)

Nesha Zoric
Nesha Zoric

Reputation: 6620

We had the same problem with finding the right way on how to test our GraphQL SailsJS app. Combination of chai, mocha, and supertest seemed like the best solution. In this article there's a full example of how to configure everything and a full test example, so check it out to get a better idea of how to do it. Also, documentation on mocha, chai and supertest will be useful as well.

Upvotes: 2

piotrbienias
piotrbienias

Reputation: 7401

In order to test each endpoint of your service, you need to perform a POST operation on specified URL with proper payload. The payload should be an object containing three attributes

  • query - this is a GraphQL query that will be run on the server side
  • operationName - name of the operation from query to be run
  • variables - used in the query

In order to test your endpoint you can use module like supertest that allows you to perform requests like GET, POST, PUT etc.

import request from 'supertest';

let postData = {
    query: `query returnUser($id: Int!){
                returnUser(id: $id){
                    id
                    username
                    email
                }
            }`,
    operationName 'returnUser',
    variables: {
        id: 1
    }
};

request(graphQLEndpoint)
    .post('?')
    .send(postData)
    .expect(200) // status code that you expect to be returned
    .end(function(error, response){
        if ( error ) console.log(error);

        // validate your response
    });

In such a way you can test every query and mutation your service contains by performing POST requests with equivalent postData objects having proper attributes. To wrap all those tests together you can use any test framework working under Node.js like Mocha with use of assertion libraries.

Upvotes: 2

Related Questions