Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 380
Steve Y. Avatar asked Aug 11 '26 09:08

Steve Y.


1 Answers

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.

like image 166
piotrbienias Avatar answered Aug 12 '26 22:08

piotrbienias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!