Jest .toThrow
没有反应抛出错误('一些文字')
此代码产生异常
if (!['diff', 'plain', 'json'].includes(format.toLowerCase())) {
throw Error('Wrong format');
}
我正试图在测试中处理它
test('tree, yml, plan, Exception_', () => {
const fileName1 = '__tests__/__fixtures__/before.json';
const fileName2 = '__tests__/__fixtures__/after.jso';
expect(genDiff(fileName1, fileName2)).toThrow();
});
但是这个测试失败了
这很奇怪,因为这是正确处理的:
test('t', () => {
expect(() => {
throw Error();
}).toThrow();
});
如何解决这个问题?
这是功能
const genDiff = (fileName1, fileName2, format = 'diff') => {
const wrongFiles = checkForWrongFiles([fileName1, fileName2]);
if (wrongFiles.length !== 0) {
const errorMessage = `Could not find this files:\n ${wrongFiles.join('\n')}`;
throw errorMessage;
}
if (!['diff', 'plain', 'json'].includes(format.toLowerCase())) {
throw Error('Wrong format');
}
...
return result;
};
你必须将调用包装到抛出的函数,否则错误is not catched by the assertions(参见底部的注释)。请注意,我已经在函数中包含了对genDiff
的调用。
test('tree, yml, plan, Exception_', () => {
const fileName1 = '__tests__/__fixtures__/before.json';
const fileName2 = '__tests__/__fixtures__/after.jso';
expect(() => genDiff(fileName1, fileName2)).toThrow();
});