首页 > 解决方案 > 重新渲染组件后如何使酶预期错误

问题描述

我想做一些类似于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实际异常执行一些操作的正确方法是什么?

标签: reactjsjestjsenzyme

解决方案


我最终使用手动触发了被测组件的重新渲染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);
    });
});

推荐阅读