typescript 异步 componentDidMount 时使用 React 的 Jest 和 Enzyme 进行测试
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/49419961/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Testing with React's Jest and Enzyme when async componentDidMount
提问by Whj
- react:16.3.0-alpha.1
 - jest: "22.3.0"
 - enzyme: 3.3.0
 - typescript: 2.7.1
 
- 反应:16.3.0-alpha.1
 - 开玩笑:“22.3.0”
 - 酶:3.3.0
 - 打字稿: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
回答by Whj
Solution:
解决方案:
1: use the async/await syntax.
1:使用 async/await 语法。
2: Use mount (no shallow).
2:使用mount(不浅)。
3: await async componentLifecycle.
3:等待异步组件生命周期。
For ex:
例如:
    test(' ',async () => {
      const wrapper = mount(
         <Foo />
      );
      await wrapper.instance().componentDidMount();
    })
回答by VivekN
Something like this should work for you:-
这样的事情应该对你有用:-
 describe('...', () => {
   test('...', async () => {
     const wrapper = await mount(<Foo/>);
     expect(wrapper.instance().bar).toBe(100);
   });
 });
回答by uberdandy
Try this:
试试这个:
it('should do something', async function() {
  const wrapper = shallow(<Foo />);
  await wrapper.instance().componentDidMount();
  app.update();
  expect(wrapper.instance().bar).toBe(100);
});
回答by Tobias Weibel
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-7c4c99e77d2dwhich fixed my problems.
这里提供的解决方案都没有解决我的所有问题。最后我发现https://medium.com/@lucksp_22012/jest-enzyme-react-testing-with-async-componentdidmount-7c4c99e77d2d解决了我的问题。
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);
});
回答by Ignacio
Your test also needs to implement async, await.
For ex:
您的测试还需要实现 async、await。
例如:
  it('should do something', async function() {
    const wrapper = shallow(<Foo />);
    const result = await wrapper.instance();
    expect(result.bar).toBe(100);
  });

