我有一个简单的函数,如果输入低于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的输入测试这个功能,比如:
import { hoursMinutesSecondsFromSeconds } from './timetools';
describe('hoursMinutesSecondsFromSeconds', () => {
it('throws error', () => {
expect(hoursMinutesSecondsFromSeconds(-2)).toThrowError('illegal inputSeconds < 0');
});
});
但是,当我运行这个测试时,测试失败了,我收到一条错误消息:
Error: illegal inputSeconds < 0
为什么它没有通过测试,当它抛出一个错误时,就像我期望它在测试中抛出的一样?
在JavaScript中,如果不使用try..catch
包装错误,就不可能处理像expect(hoursMinutesSecondsFromSeconds(-2))
一样抛出的错误。
toThrowError
应该与调用时内部封装有try..catch
的函数一起使用。应该是:
expect(() => hoursMinutesSecondsFromSeconds(-2)).toThrowError('illegal inputSeconds < 0');
查看:https://jestjs.io/docs/en/expect#tothrowerror我预计您需要将函数调用封装在一个函数中。
类似:
expect(() => {
hoursMinutesSecondsFromSeconds(-2);
}).toThrowError('illegal inputSeconds < 0');