【发布时间】:2020-02-28 09:31:07
【问题描述】:
我正在尝试通过使用 jest.fn(() => Promise.resolve(["FAQ 1"])); 模拟 DB 调用来为 NodeJS API 编写单元测试用例
我的 API 工厂文件是这样的:
const getFAQ=(request,reply)=>{
faqs.findByCondition(request.params.filter,success=>{
reply(Response.sendResponse(true, success, ResponseMessages.SUCCESS, StatusCodes.OK));
}, error => {
log.error('ERROR : ', error);
reply(Response.sendResponse(false, error, ResponseMessages.ERROR, 400));
});
};
我的模型 JS 包含 findByCondition() 是这样的:
findByCondition = (condition, success_callback, error_callback) => {
"use strict";
faq.find(condition, (err, docs) => {
if (err) {
error_callback(err);
} else {
success_callback(docs);
}
});
}
我尝试编写单元测试用例如下:
describe("test cases for FAQ Factory", () => {
utils.callAPI = jest.fn(() => 'test')
test('getFAQ Success Case', (done) => {
const request = {
params: {
filter: 'all'
},
headers: {
authorization: 'asfasfasdfas'
}
}
faqModel.findByCondition = jest.fn(() => Promise.resolve(["FAQ 1"]));
faqFactory.getFAQ(request, (result) => {
expect(result).toBeDefined();
expect(result.status_code).toBe(200);
})
})
});
我能够成功运行测试用例,但代码覆盖率未涵盖成功或错误回调
但如果我将我的 API Factory 更改为这样的东西,同样的测试用例也可以工作:
const getFAQ = (request, reply) => {
faqs.findByCondition(request.params.filter).then(success => {
reply(Response.sendResponse(true, success, ResponseMessages.SUCCESS, StatusCodes.OK));
}).catch(error => {
log.error('ERROR : ', error);
reply(Response.sendResponse(false, error, ResponseMessages.ERROR, 400));
});
};
有什么方法可以让我编写测试用例以覆盖成功/错误回调?
【问题讨论】:
标签: javascript node.js unit-testing jestjs