【问题标题】:How to mock mongodb for unit testing graphql resolver如何模拟 mongodb 以进行单元测试 graphql 解析器
【发布时间】:2019-02-22 14:52:51
【问题描述】:

我正在学习 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 -->
}

【问题讨论】:

    标签: node.js mongodb unit-testing mongoose graphql


    【解决方案1】:

    您正在寻找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 所做的那样。

    【讨论】:

      【解决方案2】:

      您可以使用 graphql-tools here is a link to the blog

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

      【讨论】:

      • graphql-tools 允许你创建一个 mockServer。问题是关于在服务器中模拟对 MongoDB within 的调用。
      猜你喜欢
      • 2018-11-21
      • 1970-01-01
      • 1970-01-01
      • 2013-04-01
      • 2013-11-18
      • 1970-01-01
      • 2018-04-04
      • 2021-09-27
      • 1970-01-01
      相关资源
      最近更新 更多