gpt4 book ai didi

node.js - 如何模拟 mongodb 以进行单元测试 graphql 解析器

转载 作者:太空宇宙 更新时间:2023-11-03 22:22:34 24 4
gpt4 key购买 nike

我正在学习 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 所做的那样如上所述。

关于node.js - 如何模拟 mongodb 以进行单元测试 graphql 解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52388777/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com