异步组件时使用React的Jest和酶进行测试 [英] Testing with React's Jest and Enzyme when async componentDidMount

查看:355
本文介绍了异步组件时使用React的Jest和酶进行测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • 反应:16.3.0-alpha.1
  • 笑话:"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

推荐答案

解决方案:

1:使用async/await语法.

1: use the async/await syntax.

2:使用安装(不浅).

2: Use mount (no shallow).

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

3: await async componentLifecycle.

例如:

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

这篇关于异步组件时使用React的Jest和酶进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆