我有以下thunk:
export const deleteUser = (id: number) => (dispatch: ThunkDispatch<{}, {}, AnyAction>) =>
axiosInstance.delete(`users/${id}`)
.then(() => dispatch(deleted(id)))
我测试过这个暴徒:
it('creates DELETED action when user is deleted', () => {
const deleteId: number = 1
axiosInstance.delete.mockResolvedValue({})
const expectedActions = [ deleted(deleteId) ];
const store = mockStore();
return store.dispatch(deleteUser(deleteId)).then(() => {
expect(store.getActions()).toEqual(expectedActions)
});
});
现在我正在测试一个发送这个砰的一声的按钮。我可以复制以前的方法(将调度的操作与预期的调度操作进行比较(,但这似乎没有必要,因为我已经测试了thunk。它还需要进行更多的测试设置(例如模拟axios(
我所需要做的就是测试按钮是否用这个thunk调用dispatch
。我试过
beforeEach(() => {
store = mockStore({ users: userList })
store.dispatch = jest.fn()
render(<Provider store={store}><UserTable /></Provider>)
});
it('should dispatch delete thunk when the delete button is clicked', () =>
fireEvent.click(screen.getByRole('button', {name: /delete user 1/i}))
expect(store.dispatch).toHaveBeenCalledTimes(1)
expect(store.dispatch).toHaveBeenCalledWith(deleteUser(1))
})
但是expect(store.dispatch).toHaveBeenCalledWith(deleteUser(1))
失败了,因为您无法比较匿名函数。
还有其他方法吗,或者我需要"重新测试"组件中的thunk吗?
仔细思考后,检查是否在此处发送了thunk并没有多大意义。我采用了将要测试的组件与连接的组件分离的方法-请参阅https://stackoverflow.com/a/35578985/11550924.这使我可以编写类似的测试
const mockDeleteUser = jest.fn()
it('should call deleteUser when delete button is clicked', () => {
render(<UserTable users={userList} deleteUser={mockDeleteUser} />)
fireEvent.click(screen.getByRole('button', {name: /delete user 1/i}))
expect(mockDeleteUser).toHaveBeenCalledTimes(1)
expect(mockDeleteUser).toHaveBeenCalledWith(1)
})
也就是说,我不是嘲笑调度函数并检查deleteUser
thunk是否到达那里,而是嘲笑deleteUser
并检查它是否被调用。然后可以在E2E测试中对连接的部件进行测试。