我试图通过使用jest.fn(() => Promise.resolve(["FAQ 1"]));
来模拟数据库调用来编写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));
});
};
我的包含findByCondition()
的Model JS如下所示:
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));
});
};
有什么办法可以编写测试用例,使其涵盖成功/错误回调?
答案 0 :(得分:0)
基本上,如果您想测试两种情况并将回调传递给findByCondition
,则必须重写getFAQ
为了使我的意思更清楚,我对其进行了一些简化。
const getFAQ = (request, reply) => {
faqs
.findByCondition(request.params.filter)
.then(success => {
reply(true);
})
.catch(error => {
reply(false);
});
};
const faqs = {
findByCondition: () => {
return Promise.resolve();
}
};
it("works", () => {
jest.spyOn(faqs, `findByCondition`).mockResolvedValue({});
getFAQ({ params: { filter: "hello" } }, reply => {
expect(reply).toBe(true);
});
});
it("doesn't work", () => {
jest.spyOn(faqs, `findByCondition`).mockRejectedValue(new Error(`This fails because of error`));
getFAQ({ params: { filter: "hello" } }, reply => {
expect(reply).toBe(false);
});
});
您可以看到它here
答案 1 :(得分:0)
更新: 我已经通过使用mockingoose库找到了一个解决方案,将我的测试用例编写如下:
test("test to getFAQ Success", async (done) => {
const request = {
params: {
filter: 'all'
},
headers: {
authorization: testData.authorization
}
}
mockingoose(faqModel.faq).toReturn([], 'find');
const result = await promisify(faqFactory.getFAQ, request);
expect(result).toBeDefined();
expect(result.status).toEqual(200);
done();
})