简体   繁体   English

如何模拟mongodb进行单元测试graphql解析器

[英]How to mock mongodb for unit testing graphql resolver

I am learning graphql and want to do the unit testing for my resolver ( ie the query to get "answers").The problem is my resolver use mongoose to query data from mongodb behind the scene and I dont know how to mock these calls. 我正在学习graphql并想对我的解析器进行单元测试(即查询以获取“答案”)。问题是我的解析器使用mongoose从幕后的mongodb中查询数据,并且我不知道如何模拟这些调用。

Could anyone help me with this ? 有人可以帮我吗? Thank you. 谢谢。

The resolver for my query is sth like this: 我的查询的解析器是这样的:

const { Book, Author } = require('../models')    

module.exports = {
  answers: async ( parent, { searchText } ) => {        
    let authors = null;
    let books = null;
    try {
        authors = await Author.find({});            
        books = await Book.find({}); 
        return getAnswers(authors,books, searchText);
    }catch (err) {
        console.log(err);
    }        
    return null;
 }
}

function getAnswers(books,authors,text) {
    <!-- process data here -->
}

You are looking for proxyquire . 您正在寻找proxyquire It lets you override the dependencies in a file you require. 它使您可以覆盖所需文件中的依赖项。 Your test file could look something like this 您的测试文件可能看起来像这样

const proxyquire = require('proxyquire');
const mockBook = {...}

describe('Test #1', function() {
    const stubs = {
        '../models': {
            Book: {
                find: () => Promise.resolve(mockBook),
            },
            Author: // Same as book
        },
    };

    const myfile = proxyquire('./myfile', stubs);
    let answers;

    before(async function() {
        answers = await myfile.answers();
    });

    describe("should succeed", function() {
        expect(answers).to.be.equal(ExpectedAnswers);
    });
});

Now, that code has not been run and will definitely not succeed. 现在,该代码尚未运行,并且绝对不会成功。 This was to give you an idea of how to use proxyquire. 这是为了让您了解如何使用proxyquire。

As for the getAnswers() part of the code, you will need to mock the dependencies of that function as well, like it is done for Book in the sample above. 至于代码的getAnswers()部分,您还需要模拟该函数的依赖关系,就像上面示例中对Book所做的那样。

You can use graphql-tools here is a link to the blog 您可以使用graphql-tools, 这里是博客的链接

npm install graphql-tools

import your schema into your test file 将架构导入测试文件

import { mockServer } from 'graphql-tools';
import schema from './schema.js';

describe('mock server', () => {
  it('should mock the server call', async () => {
    const myMockServer = mockServer(schema, {
      String: () => 'Hello', // <--- expecting a `hello` to be returned
    });
    const response = await myMockServer.query(`{
      users {
        username,
      }
    }`);

    const expected =  { // This shape of the data returned
      data: {
        users: [
          {
            "username": "Hello"
          },
          {
            "username": "Hello"
          },
       ]
    }
  }
  expect(response).toMatchObject(expected);
});
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM