Testing with React's Jest and Enzyme when async componentDidMount

Whj picture Whj · Mar 22, 2018 · Viewed 13.8k times · Source
  • react:16.3.0-alpha.1
  • jest: "22.3.0"
  • enzyme: 3.3.0
  • typescript: 2.7.1

code:

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

test:

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

Error:

Expected value to be:
  100
Received:
  0

Answer

Whj picture Whj · Mar 28, 2018

Solution:

1: use the async/await syntax.

2: Use mount (no shallow).

3: await async componentLifecycle.

For ex:

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