1 回答

TA貢獻1827條經(jīng)驗 獲得超4個贊
副作用是否在構造函數(shù)中正確完成。這是您案例的單元測試解決方案:
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
添加回答
舉報