Reactjs 如何使组件重新渲染后出现错误

Reactjs 如何使组件重新渲染后出现错误,reactjs,jestjs,enzyme,Reactjs,Jestjs,Enzyme,我想做一些类似于另一个问题的事情 想象一下我有一个这样的测试 const TestComponent = () => { if (someCondition) { throw new Error('Test error'); } else { return <div> bla </div> } } describe('Test Component', () => { it('Throws an error', ()

我想做一些类似于另一个问题的事情

想象一下我有一个这样的测试

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
    });
});
const TestComponent=()=>{
如果(某些条件){
抛出新错误(“测试错误”);
}否则{
返回bla
}
}
描述('测试组件',()=>{
它('抛出错误',()=>{
设分量=浅();
//执行一些将导致组件重新渲染的设置
//然后通过一些条件分支
试一试{
component.update();
}捕捉(错误){
//在这里断言错误
}
//在这里,我想以某种方式断言组件在重新渲染期间引发了异常
});
});
目前,我的代码没有到达catch子句,整个测试用例失败,错误来自
TestComponent
我不确定catch为什么没有捕获到它。断言重新呈现的组件已引发异常并对实际异常执行某些操作的正确方法是什么

您必须将代码包装在函数中,否则错误将不会被捕获,断言将失败

因此,您可以:

describe('Test Componnet', () => {
  it('should throw error', () => {
    expect(() => shallow(<TestComponent />)).toThrowError();
  }
}
description('testcomponent',()=>{
它('应该抛出错误',()=>{
expect(()=>shall()).tothrower();
}
}
在代码中,“捕获未捕获”,因为错误是从
浅层执行中抛出的,而try-catch块没有执行


看看

我最终使用
Component.instance().render()

类TestComponent扩展组件{
//其他一些事情
render(){
if(this.state.someCondition){
抛出新错误(“测试错误”);
}否则{
返回bla
}
}
}
描述('测试组件',()=>{
它('抛出错误',()=>{
设分量=浅();
//在TestComponent中触发设置状态的一些代码
//将“someCondition”设置为true,从而触发重新渲染,这将引发错误
让caughtErrorsCount=0;
试一试{
component.instance().render();
}捕捉(错误){
//在这里断言错误
期望(错误)。toEqual(期望错误);
caughtErrorsCount+=1;
}
expect(caughterrorscont).toBe(1);
});
});

只需移动
浅(…)
内部的
尝试{…}
块,但问题是在我第一次调用
浅(
组件.update()
有些代码将更改组件的状态并触发重新渲染,第二次重新渲染是我希望抛出错误的代码。
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);
    });
});