重新渲染组件后如何使酶预期错误

时间:2019-08-05 16:04:04

标签: reactjs jestjs enzyme

我想对另一个问题做类似this answer的事情

想象一下我有这样的测试

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的正确方法是什么?

2 个答案:

答案 0 :(得分:0)

the toThrowError documentation

中所述
  

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

因此您可以:

describe('Test Componnet', () => {
  it('should throw error', () => {
    expect(() => shallow(<TestComponent />)).toThrowError();
  }
}

在您的代码中“捕获未捕获” ,因为在shallow执行中抛出了错误,并且try-catch块未在执行。

看看this working example

答案 1 :(得分:0)

我最终使用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);
    });
});