我正在尝试对该功能进行全面介绍,但似乎无法模拟该功能,因此它会调用onSuccess
回调
代码
export const handleDelete = (action) => {
const { id, type, actions } = action;
actions.dispatch(
actions.openDialog(`delete${type}`, Dialog, {
onSuccess: () => {
actions.dispatch(actions.thunk(id));
actions.notify(`${type} deleted`, {
variant: 'success',
});
},
body: `Are you sure you want to delete this ${type}?`,
title: `Delete ${type}`,
confirm: 'Delete',
cancel: 'Cancel',
danger: true,
})
);
};
单元测试:
it('should handle delete', () => {
const mockDispatch = jest.fn();
const mockOnSuccess = jest.fn();
const mockOpenDialog = jest.fn(() => ({
onSuccess: mockOnSuccess,
}));
const mockAction = {
id: 1,
type: 'example',
actions: {
dispatch: mockDispatch,
openDialog: mockOpenDialog,
},
};
handleDelete(mockAction);
expect(mockDispatch).toHaveBeenCalled();
expect(mockOpenDialog).toHaveBeenCalled();
});
覆盖率:
答案 0 :(得分:1)
单元测试解决方案:
index.ts
:
export const handleDelete = (action) => {
const { id, type, actions } = action;
const Dialog = 'Dialog';
actions.dispatch(
actions.openDialog(`delete${type}`, Dialog, {
onSuccess: () => {
actions.dispatch(actions.thunk(id));
actions.notify(`${type} deleted`, {
variant: 'success',
});
},
body: `Are you sure you want to delete this ${type}?`,
title: `Delete ${type}`,
confirm: 'Delete',
cancel: 'Cancel',
danger: true,
}),
);
};
index.test.ts
:
import { handleDelete } from './';
describe('64803187', () => {
it('should pass', () => {
const action = {
id: '1',
type: 'user',
actions: {
dispatch: jest.fn(),
openDialog: jest.fn().mockImplementationOnce((type, dialog, options) => {
options.onSuccess();
return { type: 'OPEN_DIALOG' };
}),
notify: jest.fn(),
thunk: jest.fn().mockReturnValueOnce({ type: 'DELETE_USER_SUCCESS' }),
},
};
handleDelete(action);
expect(action.actions.dispatch).toBeCalledWith({ type: 'OPEN_DIALOG' });
expect(action.actions.openDialog).toBeCalledWith('deleteuser', 'Dialog', {
onSuccess: expect.any(Function),
body: `Are you sure you want to delete this user?`,
title: `Delete user`,
confirm: 'Delete',
cancel: 'Cancel',
danger: true,
});
expect(action.actions.dispatch).toBeCalledWith({ type: 'DELETE_USER_SUCCESS' });
expect(action.actions.notify).toBeCalledWith('user deleted', { variant: 'success' });
});
});
单元测试结果:
PASS src/stackoverflow/64803187/index.test.ts
64803187
✓ should pass (8ms)
----------|----------|----------|----------|----------|-------------------|
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.267s, estimated 13s