javascript - 在 JEST-Enzyme 中编写测试用例,以便在构造函数中调用 Promise

标签 javascript reactjs jestjs es6-promise enzyme

我需要为 React 类组件编写渲染测试用例,该组件具有在构造函数中调用的 promise 。

React类组件的构造函数:

constructor(props) {
    super(props);
    this.props.getPaypalAuthUrl().then((result) => {
        this.setState({authUrl: result})
    });
}

我的测试用例:

test(testIDAndStatement.settings.TC086, async () => {
        const wrapper = await shallow(<Payment getPaypalAuthUrl={getPaypalAuthUrl}/>);
        const instance = wrapper.instance();
        instance.constructor();
        wrapper.setState({ connectedToPaypal: true });
        const paymentComponent = wrapper.find('.settings-payment__wrapper');
        expect(paymentComponent.length).toBe(1);
    });

获取错误:

TypeError: this.props.getPaypalAuthUrl(...).then is not a function

我尝试过的解决方案:我尝试使用 async-await 编写测试用例,并尝试获取构造函数的实例,就像我们为生命周期或普通方法获取的那样。

最佳答案

副作用是否在构造函数中正确完成。 这是适合您的案例的单元测试解决方案:

index.jsx:

import React, { Component } from 'react';

class SomeCompoennt extends Component {
  constructor(props) {
    super(props);
    this.state = { authUrl: '' };
    this.props.getPaypalAuthUrl().then((result) => {
      this.setState({ authUrl: result });
    });
  }
  render() {
    return <div>some component</div>;
  }
}

export default SomeCompoennt;

index.spec.jsx:

import SomeCompoennt from './index';
import React from 'react';
import { shallow } from 'enzyme';

describe('58877501', () => {
  it('should pass', async () => {
    const mProps = {
      getPaypalAuthUrl: jest.fn().mockResolvedValueOnce('http://github.com'),
    };
    const wrapper = shallow(<SomeCompoennt {...mProps}></SomeCompoennt>);
    expect(wrapper.text()).toBe('some component');
    expect(wrapper.state()).toEqual({ authUrl: '' });
    await new Promise((resolve) => setTimeout(resolve));
    expect(wrapper.state()).toEqual({ authUrl: 'http://github.com' });
  });
});

100%覆盖率的单元测试结果:

 PASS  src/stackoverflow/58877501/index.spec.tsx (10.985s)
  58877501
    ✓ should pass (24ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |      100 |      100 |      100 |      100 |                   |
 index.jsx |      100 |      100 |      100 |      100 |                   |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        12.808s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58877501

关于javascript - 在 JEST-Enzyme 中编写测试用例,以便在构造函数中调用 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58877501/

相关文章:

javascript - 推送事件后来自 serviceWorker 的 PostMessage

reactjs - 如何将窗口调整大小事件监听器值设置为 react 状态?

javascript - 如何循环遍历对象数组中的数组

angular - 使用 NzModalFooterDirective 时测试组件

javascript - 在 JS AudioContext.analyserNode 中确定频率

javascript - TypeError : this. props.data.map 不是一个函数,但数据是一个列表

javascript - 使用 Jest 模拟依赖项中的依赖项?

unit-testing - 运行时错误运行 Jest : in React

javascript - 类型错误:无法读取未定义的 React 属性 'any'

javascript - Ava 单元测试因 TypeScript 失败 ("SyntaxError: Unexpected identifier")