[英]Jest - Testing function that throws an error not working
我有一个简单的 function,如果输入低于 0,它会抛出错误:
export const hoursMinutesSecondsFromSeconds = (inputSeconds) => {
if (inputSeconds < 0) {
throw new Error('illegal inputSeconds < 0');
}
let rem = Math.abs(inputSeconds);
let divisor = 3600;
const result = [];
while (divisor >= 1) {
result.push(Math.floor(rem / divisor));
rem = rem % divisor;
divisor = divisor / 60;
}
return result;
};
我正在尝试使用低于 0 的输入来测试此 function,如下所示:
import { hoursMinutesSecondsFromSeconds } from './timetools';
describe('hoursMinutesSecondsFromSeconds', () => {
it('throws error', () => {
expect(hoursMinutesSecondsFromSeconds(-2)).toThrowError('illegal inputSeconds < 0');
});
});
但是,当我运行此测试时,测试失败并且我收到一条错误消息:
Error: illegal inputSeconds < 0
为什么这没有通过测试,当它抛出一个错误时,就像我期望它在我的测试中抛出的一样?
在 JavaScript 中不可能处理像expect(hoursMinutesSecondsFromSeconds(-2))
这样抛出的错误而不用try..catch
包装它。
toThrowError
应该与 function 一起使用,它在调用时在内部用try..catch
包装。 它应该是:
expect(() => hoursMinutesSecondsFromSeconds(-2)).toThrowError('illegal inputSeconds < 0');
查看: https://jestjs.io/docs/en/expect#tothrowerror我希望您需要将 function 调用包装在 function 中。
像:
expect(() => {
hoursMinutesSecondsFromSeconds(-2);
}).toThrowError('illegal inputSeconds < 0');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.