更新时间:2022-11-04 12:12:42
意识到这是一个老问题,但是对于将来的观众来说,我认为我会扩展@galki的答案.除了使用try/catch之外,您还可以简单地将shallow
/mount
包装在一个匿名函数中,然后使用.toThrowError()
:
Realise this is an old question, but for future viewers, I thought I'd expand on @galki's answer. Rather than using a try/catch, you could simply wrap your shallow
/mount
in an anonymous function and then use .toThrowError()
instead:
const TestComponent = () => {
throw new Error('Test error');
}
describe('Test Component', () => {
it('Throws an error', () => {
expect(() => shallow(<TestComponent />)).toThrowError();
});
});
这为您提供了更简洁的代码,并且结果相同.
This gives you much cleaner code, with the same result.