我将使用enzyme 库来测试您的组件。为了保证使用async/await语法的componentDidMount生命周期方法的异步任务执行完成,我们需要刷新promise队列。
有关刷新承诺队列如何做的更多信息,请参阅macrotasks-and-microtasks
所有微任务在任何其他事件处理或渲染或任何其他宏任务发生之前完成。
这意味着async/await 和promise 是微任务,它们将在setTimeout 创建的宏任务之前完成。
例如
index.tsx:
import React from 'react';
import { getData } from './services/DataService';
export function withData(WrappedComponent, count) {
return class extends React.Component {
state = {
data: [],
};
async componentDidMount() {
this.setState({
data: await getData(count),
});
}
render() {
const { data } = this.state;
return data.length > 0 && <WrappedComponent data={data} />;
}
};
}
index.test.tsx:
import React from 'react';
import { withData } from './';
import { getData } from './services/DataService';
import { shallow } from 'enzyme';
import { mocked } from 'ts-jest/utils';
jest.mock('./services/DataService');
const mockedGetData = mocked(getData);
class MockedComponent extends React.Component {
render() {
return <div>mocked component</div>;
}
}
function flushPromises() {
return new Promise((resolve) => setTimeout(resolve, 0));
}
describe('66260393', () => {
afterAll(() => {
jest.resetAllMocks();
});
it('should render wrapped component', async () => {
mockedGetData.mockResolvedValueOnce('fake data');
const WithDataComponent = withData(MockedComponent, 1);
const wrapper = shallow(<WithDataComponent></WithDataComponent>);
expect(wrapper.state('data')).toEqual([]);
await flushPromises();
expect(wrapper.state('data')).toEqual('fake data');
expect(wrapper.find(MockedComponent)).toBeTruthy();
expect(wrapper.find(MockedComponent).prop('data')).toEqual('fake data');
});
});
单元测试结果:
PASS examples/66260393/index.test.tsx
66260393
✓ should render wrapped component (23 ms)
-------------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-------------------|---------|----------|---------|---------|-------------------
All files | 90 | 100 | 80 | 90 |
66260393 | 100 | 100 | 100 | 100 |
index.tsx | 100 | 100 | 100 | 100 |
66260393/services | 50 | 100 | 0 | 50 |
DataService.ts | 50 | 100 | 0 | 50 | 2
-------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 3.198 s