Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing with React's Jest and Enzyme when async componentDidMount

  • 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
like image 231
Whj Avatar asked Mar 22 '18 03:03

Whj


People also ask

Can we use both Enzyme and react testing library?

There are many React testing libraries on the market, but two of the most popular are React Testing Library (RTL) and Enzyme. Both of them are used for testing react components, and both provide the tools needed for testing some application, but they have two different approaches.

How do you test for Jest and enzymes?

Both Jest and Enzyme are meant to test the react applications. Jest can be used with any other Javascript framework, but Enzyme is meant to run on react only. Jest can be used without Enzyme, and snapshots can be created and tested perfectly fine. But the Enzyme adds additional functionality to it.


2 Answers

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();
    })
like image 56
Whj Avatar answered Sep 29 '22 01:09

Whj


Something like this should work for you:-

 describe('...', () => {
   test('...', async () => {
     const wrapper = await mount(<Foo/>);
     expect(wrapper.instance().bar).toBe(100);
   });
 });
like image 23
VivekN Avatar answered Sep 29 '22 00:09

VivekN