axios-mock-adapter
axios-mock-adapter copied to clipboard
NetworkError Behaves Different with onPost than Other HTTP Methods
I was attempting to write a unit test for a React hook and I've been unable to determine why networkError is caught in the methods onGet, onPatch, and onDelete but not when using onPost. My unit test is failing because the error is not being caught and is described as follows:
it('does not add a user on a failed request', async () => {
const queryClient = new QueryClient();
const mock = new MockAdapter(axios);
queryClient.setQueryData('manageable-users', mockUsers);
mock.onPost('/api/users').networkErrorOnce();
const wrapper = ({ children }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
const { result, waitForNextUpdate } = renderHook(() => useCreateUser(), {
wrapper,
});
act(() => {
result.current.mutate({
firstName: 'New',
lastName: 'User',
userName: '[email protected]',
});
});
await waitForNextUpdate();
const updatedUserList = queryClient.getQueryData('manageable-users');
expect(updatedUserList.length).toEqual(4);
expect(updatedUserList).not.toEqual(
expect.arrayContaining([
expect.objectContaining({
userName: '[email protected]',
}),
])
);
});
Axios errors are successfully caught with the following uses of my mock:
mock.onGet('api/users').networkErrorOnce()
mock.onDelete('api/users/642').networkErrorOnce()
mock.onPost('api/users').reply(400)
mock.onPost('api/users', function() {return Promise.reject();})
The network error and timeout are not caught:
mock.onPost('/api/users').networkErrorOnce();
mock.onPost('/api/users').networkError();
mock.onPost('/api/users').timeout();
Is there any reason why onPost would be incompatible with the networkError methods or have I configured something incorrectly?