在JEST-Enzyme中编写测试用例以在构造函数中调用promise

问题描述 投票:0回答:1

我需要为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(...)。然后不是函数

我尝试过的解决方案:我尝试用async-await编写测试用例,并尝试获取构造函数的实例,就像我们在生命周期或常规方法中获得的一样。

javascript reactjs jestjs es6-promise enzyme
1个回答
1
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.