我正在学习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 -->
}
答案 0 :(得分:0)
您正在寻找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
所做的那样。
答案 1 :(得分:0)
您可以使用 graphql工具 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);
});
});