Testing with React's Jest and Enzyme when async componentDidMount

怎甘沉沦 提交于 2019-12-03 19:30:25

问题


  • 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

回答1:


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();
    })



回答2:


Something like this should work for you:-

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



回答3:


Try this:

it('should do something', async function() {
  const wrapper = shallow(<Foo />);
  await wrapper.instance().componentDidMount();
  app.update();
  expect(wrapper.instance().bar).toBe(100);
});



回答4:


Your test also needs to implement async, await.
For ex:

  it('should do something', async function() {
    const wrapper = shallow(<Foo />);
    const result = await wrapper.instance();
    expect(result.bar).toBe(100);
  });



回答5:


None of the solutions provided here fixed all my issues. At the end I found https://medium.com/@lucksp_22012/jest-enzyme-react-testing-with-async-componentdidmount-7c4c99e77d2d which fixed my problems.

Summary

function flushPromises() {
    return new Promise(resolve => setImmediate(resolve));
}

it('should do someting', async () => {
    const wrapper = await mount(<Foo/>);
    await flushPromises();

    expect(wrapper.instance().bar).toBe(100);
});


来源:https://stackoverflow.com/questions/49419961/testing-with-reacts-jest-and-enzyme-when-async-componentdidmount

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!