在异步componentDidMount时使用React的Jest和Enzyme进行测试

Whj*_*Whj 11 typescript reactjs jestjs enzyme

  • 反应:16.3.0-alpha.1
  • 开玩笑:"22.3.0"
  • 酶:3.3.0
  • 打字稿:2.7.1

码:

class Foo extends React.PureComponent<undefined,undefined>{
   bar:number;
   async componentDidMount() {
     this.bar = 0;
     let echarts = await import('echarts'); // async import
     this.bar = 100;
   }
}
Run Code Online (Sandbox Code Playgroud)

测试:

describe('...', () => {
  test('...', async () => {
    const wrapper = shallow(<Foo/>);
    const instance = await wrapper.instance();
    expect(instance.bar).toBe(100);
  });
});
Run Code Online (Sandbox Code Playgroud)

错误:

Expected value to be:
  100
Received:
  0
Run Code Online (Sandbox Code Playgroud)

Whj*_*Whj 20

解:

1:使用async/await语法.

2:使用mount(不浅).

3:等待异步组件生命周期.

例如:

    test(' ',async () => {
      const wrapper = mount(
         <Foo />
      );
      await wrapper.instance().componentDidMount();
    })
Run Code Online (Sandbox Code Playgroud)

  • 这将导致该方法运行两次. (10认同)

Viv*_*ekN 12

这样的事情应该为您工作:

 describe('...', () => {
   test('...', async () => {
     const wrapper = await mount(<Foo/>);
     expect(wrapper.instance().bar).toBe(100);
   });
 });
Run Code Online (Sandbox Code Playgroud)

  • 确实; 如果组件的`didMount`中有`setState`,则需要在`expect`之前添加`wrapper.update();`。 (2认同)