繁体   English   中英

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

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

我正在学习graphql并想对我的解析器进行单元测试(即查询以获取“答案”)。问题是我的解析器使用mongoose从幕后的mongodb中查询数据,并且我不知道如何模拟这些调用。

有人可以帮我吗? 谢谢。

我的查询的解析器是这样的:

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

您正在寻找proxyquire 它使您可以覆盖所需文件中的依赖项。 您的测试文件可能看起来像这样

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

现在,该代码尚未运行,并且绝对不会成功。 这是为了让您了解如何使用proxyquire。

至于代码的getAnswers()部分,您还需要模拟该函数的依赖关系,就像上面示例中对Book所做的那样。

您可以使用graphql-tools, 这里是博客的链接

npm install graphql-tools

将架构导入测试文件

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