小编典典

异步组件时使用React的Jest和酶进行测试

reactjs

  • react:16.3.0-alpha.1
  • jest: “22.3.0”
  • enzyme: 3.3.0
  • typescript: 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;
   }
}

测试:

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

错误:

Expected value to be:
  100
Received:
  0

阅读 309

收藏
2020-07-22

共1个答案

小编典典

解:

1:使用异步/等待语法。

2:使用安装座(不浅)。

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

例如:

    test(' ',async () => {
      const wrapper = mount(
         <Foo />
      );
      await wrapper.instance().componentDidMount();
    })
2020-07-22