gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:31:46 24 4
gpt4 key购买 nike

我需要为 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com