Unit Tests for GraphQL Node JS App

江枫思渺然 提交于 2020-07-22 02:51:08

问题


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!


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/42542917/unit-tests-for-graphql-node-js-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!