这是解决方案,mapDispatchToProps 函数只是一个 javascript 函数。您无需使用Shallow 渲染和enzyme 对其进行测试。
const ACTION_TYPES = {
SHOW_SETTINGS: 'SHOW_SETTINGS',
SET_FILTER_TEXT: 'SET_FILTER_TEXT',
SET_EXPORT_COUNT: 'SET_EXPORT_COUNT'
};
export const showSettings = { type: ACTION_TYPES.SHOW_SETTINGS };
export const setFilterText = value => ({ type: ACTION_TYPES.SET_FILTER_TEXT, payload: { value } });
export const setExportCount = () => ({ type: ACTION_TYPES.SET_EXPORT_COUNT });
export const mapDispatchToProps = dispatch => {
return {
sidebarSettings: () => {
dispatch(showSettings);
},
setFilterText: value => {
dispatch(setFilterText(value));
},
setExportCount: () => {
dispatch(setExportCount());
}
};
};
单元测试:
import { mapDispatchToProps, showSettings, setFilterText, setExportCount } from './';
const dispatch = jest.fn();
describe('mapDispatchToProps', () => {
it('t1', () => {
const actualValue = mapDispatchToProps(dispatch);
expect(Object.keys(actualValue)).toEqual(['sidebarSettings', 'setFilterText', 'setExportCount']);
actualValue.sidebarSettings();
expect(dispatch).toBeCalledWith(showSettings);
actualValue.setFilterText('name');
expect(dispatch).toBeCalledWith(setFilterText('name'));
actualValue.setExportCount();
expect(dispatch).toBeCalledWith(setExportCount());
});
});
100% 覆盖率的单元测试结果:
PASS src/stackoverflow/57802233/index.spec.ts
mapDispatchToProps
✓ t1 (11ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 4.201s