Jest中抛出Error时测试用例失败,请求排查问题
异步函数homepageHandler失败场景测试问题排查
我想要测试如下异步函数homepageHandler的失败场景:
homepageHandler: async function (req, res) { console.log(`index page. Req ${req}`); return JSON.stringify({ "message": "welcome" }); }
我通过Jest的spyOn对该函数进行mock,期望其抛出一个包含JSON对象的Error,测试代码如下:
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)
我无法定位错误原因,请问我哪里操作有误?
问题分析与修正
你的测试代码存在三个关键问题:
mock实现的参数顺序错误
原函数的参数是(req, res),但你在mock实现里写成了(res, req),虽然这不是当前报错的直接原因,但会导致后续逻辑混乱,需要修正参数顺序。异步函数的mock未遵循Promise规范
原函数是async函数,本质上会返回Promise。你直接在mock里同步抛出错误,会导致错误直接被Jest捕获为测试失败,而不会进入catch回调。正确的做法是让mock返回一个被拒绝的Promise,或者把mock实现改成async函数并抛出错误(async函数抛出错误会自动转为拒绝的Promise)。错误断言逻辑错误
你用expect(error).toBe(...)直接比较Error对象和字符串,这永远不会相等。应该断言Error对象的message属性等于目标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'); // 修正参数顺序,并用async函数实现mock mock.mockImplementation(async (req, res) => { throw new Error(JSON.stringify({ "message": "error" })); }); try { await indexControllerModule.homepageHandler(req, res); // 如果走到这里说明没抛出错误,测试失败 fail("Expected homepageHandler to throw an error"); } catch (error) { console.log(`error in accessing homepage: ${error}`); expect(error.message).toBe(JSON.stringify({ "message": "error" })); } // 测试后恢复原函数(可选,避免影响其他测试) mock.mockRestore(); }); });
额外说明
- 用
async/await替代.then/.catch让异步测试代码更易读,也符合Jest推荐的异步测试写法。 - 添加
mock.mockRestore()可以在测试结束后恢复原函数的实现,防止影响其他测试用例。
内容的提问来源于stack exchange,提问作者Manu Chadha
相关产品推荐
相关产品推荐

