GraphQL Node JS应用程序的单元测试 [英] Unit Tests for GraphQL Node JS App

查看:140
本文介绍了GraphQL Node JS应用程序的单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了带有自定义解析器的graphql节点js应用程序.谁能指出我一些说明如何为我的服务正确编写单元测试的文档?或者,如果有人以前做过,并且可以指出正确的方向,那就太好了!

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!

推荐答案

为了测试服务的每个端点,您需要在具有适当负载的指定URL上执行POST操作.有效负载应该是包含三个属性的对象

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-这是一个GraphQL查询,将在服务器端运行
  • operationName-要运行的查询中的操作的名称
  • 变量-在查询中使用

为了测试您的端点,您可以使用 supertest 之类的模块执行诸如GETPOSTPUT等的请求.

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
    });

通过对具有适当属性的等效postData对象执行POST请求,可以测试服务包含的每个querymutation.要将所有这些测试包装在一起,您可以使用断言下在Node.js下工作的任何测试框架,例如 Mocha 库.

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.

这篇关于GraphQL Node JS应用程序的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆