![](/img/trans.png)
[英]How to write a Jest-enzyme test case for code in React useEffect whose dependencies are updated in its child component
[英]Write test-case in JEST-Enzyme for promise calling in constructor
我需要为 React class 组件编写渲染测试用例,该组件具有在构造函数 function 中调用的 promise。
React class 组件的构造函数 function :
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 不是 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.