1 回答
TA贡献1827条经验 获得超4个赞
副作用是否在构造函数中正确完成。这是您案例的单元测试解决方案:
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
添加回答
举报