reactjs - 重新渲染组件后如何使酶预期错误
问题描述
我想做一些类似于this answer to another question的事情
想象一下我有一个这样的测试
const TestComponent = () => {
if (someCondition) {
throw new Error('Test error');
} else {
return <div> bla </div>
}
}
describe('Test Component', () => {
it('Throws an error', () => {
let component = shallow(<TestComponent />);
// do some setup which will cause the component to re-render
// and go through the someCondition branch
try {
component.update();
}catch(err) {
// assert the error here
}
// here I want to somehow assert that the component has thrown an exception during the re-render
});
});
目前我的代码没有到达 catch 子句,整个测试用例失败,抛出的错误是TestComponent
我不确定为什么 catch 没有捕捉到它。断言重新渲染的组件已引发异常并对expect
实际异常执行一些操作的正确方法是什么?
解决方案
我最终使用手动触发了被测组件的重新渲染component.instance().render()
class TestComponent extends Component {
// some other things
render() {
if (this.state.someCondition) {
throw new Error('Test error');
} else {
return <div> bla </div>
}
}
}
describe('Test Component', () => {
it('Throws an error', () => {
let component = shallow(<TestComponent />);
// some code which triggers a setState in the TestComponent that
// will set the `someCondition` to true, thus triggering re-render, that will throw error
let caughtErrorsCount = 0;
try {
component.instance().render();
}catch(err) {
// assert the error here
expect(err).toEqual(expectedError);
caughtErrorsCount += 1;
}
expect(caughtErrorsCount).toBe(1);
});
});
推荐阅读
- mysql - phpmyadmin 中的错误 ./libraries/plugin_interface.lib.php#551 中的警告
- c - C - 如何在 Xcode 的调试器中将指向字符串数组的指针作为数组查看
- python - python:行 concat 2 数据帧,将它们的名称保留为新列
- azure - 在 iot Central 上逐秒查看真实遥测值
- typescript - 打字稿泛型,未知的嵌套函数参数
- angularjs - 带有 iconify 图标的 AngularJS 指令不响应范围变量更改
- sql - 如何在表中插入 string_split 输出?
- javascript - 如何在使用 Angular 7 的状态更改时强制组件重新加载
- wordpress - 为什么此文本与我当前在移动版本上的设置重叠?
- python - 再次调用时将应用程序置于前台