[英]How to test catch block of a Typescript function code using mocha and chai
我有打字稿類,里面有一些功能。 每個函數都有一個 try catch 塊,當點擊 catch 時,它會返回一個預定義的響應。
我正在使用 mocha 和 chai 編寫單元測試,但在嘗試顯式命中 catch 塊時遇到了麻煩。
例如,考慮下面這個簡單的函數
public async verifyCode(email: string, code: string) {
try {
let result: CodeInterface | null = //call db to get matching code
if(result === null) {
return {status: 401, message: INCORRECT_FELLOWSHIP_CODE_MESSAGE};
}
return result._id;
} catch (error) {
Logger.log(LoggerLogTypes.ERROR, {
class_name: "LaunchServiceImpl",
function_name: "verifyFellowshipCode",
message: error.message,
stack: error.stack,
additional_info: {
code
}
});
return false;
}
}
我想編寫一個測試用例,我可以直接將控件發送到 catch 塊以獲取 false 值。 這是一個非常簡單的示例,但在其他幾個函數中,我在 catch 塊中做的更多。
我的 mocha 單元測試如下所示:
it("should go to the catch block and return false in case of exception", async function() {
let serviceInstance = new MyClass();
let response = await serviceInstance.verifyCode("john@test.com", "abc123");
// how do I directly jump to the catch block here??
expect(response).to.equal(false);
});
假設您有一個函數會拋出錯誤消息用戶未找到,因此您可以像這樣進行測試:
profileServiceInstance.getProfile('1').catch((err) => {
expect(() => {
throw err;
}).to.throw(Error, 'User not found');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.