我想测试以下函数的失败场景
homepageHandler: async function (req, res) {
console.log(`index page. Req ${req}`);
return JSON.stringify({
"message": "welcome"
});
}
我是mocking
的函数,想要throw
和Error
,其中应该有一个JSON
对象
describe("Endpoints are not accessible", () => {
it("GET request for homepage should return non-200 if error", async () => {
const baseURL = process.env.EXPRESS_SERVER_TEST
console.log(`base url is ${baseURL}`);
const req = {};
const res = {};
const mock = jest.spyOn(indexControllerModule, 'homepageHandler'); // spy on indexControllerModule's homepageHandler
mock.mockImplementation((res,req) => {
throw Error(JSON.stringify(
{
"message": "error"
}));
}); // replace implementation
indexControllerModule.homepageHandler(req,res)
.then((result)=>{
console.log(`This code path shouldn't be executed. Result is ${result}`);
})
.catch((error)=>{
console.log(`error in accessing homepage: ${error}`);
expect(error).toBe(JSON.stringify({
"message": "error"
}));
})
});
});
当我运行测试时,我得到了错误
Endpoints are not accessible › GET request for homepage should return non-200 if error
{"message":"error"}
43 |
44 | mock.mockImplementation((res,req) => {
> 45 | throw Error(JSON.stringify(
| ^
46 | {
47 | "message": "error"
48 | }))}); // replace implementation
at Object.Error (test/index.test.js:45:13)
at Object.homepageHandler (test/index.test.js:50:27)
但我不知道是什么错误。我做错了什么?
1条答案
按热度按时间kknvjkwl1#
它不起作用,因为
homepageHandler
是异步函数。你得这样嘲笑它:或更详细: