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

时间:2018-03-22 03:16:30

标签: reactjs typescript enzyme jest

  • 反应:16.3.0-alpha.1
  • jest:" 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;
   }
}

试验:

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

错误:

Expected value to be:
  100
Received:
  0

5 个答案:

答案 0 :(得分:17)

解决方案:

1:使用async / await语法。

2:使用mount(不浅)。

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

例如:

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

答案 1 :(得分:5)

这样的事情对你有用: -

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

答案 2 :(得分:2)

试试这个:

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

答案 3 :(得分:0)

您的测试还需要实现异步,等待 例如:

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

答案 4 :(得分:0)

此处提供的解决方案均未解决我的所有问题。最后,我发现https://medium.com/@lucksp_22012/jest-enzyme-react-testing-with-async-componentdidmount-7c4c99e77d2d可以解决我的问题。

摘要

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);
});
相关问题