I have the following thunk:
export const deleteUser = (id: number) => (dispatch: ThunkDispatch<{}, {}, AnyAction>) =>
axiosInstance.delete(`users/${id}`)
.then(() => dispatch(deleted(id)))
I have tested this thunk:
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)
});
});
Now I am testing a button that dispatches this thunk. I could copy the previous approach (comparing dispatched actions to expected dispatched actions) but that seems unnecessary as I've already tested the thunk. It would require doing more test setup also (e.g. mocking axios)
All I need to do is test that the button calls dispatch
with this thunk. I tried
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))
})
but expect(store.dispatch).toHaveBeenCalledWith(deleteUser(1))
fails as you can't compare anonymous functions.
Is there another way, or do I need to 'retest' the thunk in the component?