ctimmerm / axios-mock-adapter

Axios adapter that allows to easily mock requests
MIT License
3.44k stars 241 forks source link

NetworkError Behaves Different with onPost than Other HTTP Methods #297

Open faltherr opened 3 years ago

faltherr commented 3 years ago

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: 'newuser1@user.com',
      });
    });
    await waitForNextUpdate();
    const updatedUserList = queryClient.getQueryData('manageable-users');
    expect(updatedUserList.length).toEqual(4);
    expect(updatedUserList).not.toEqual(
      expect.arrayContaining([
        expect.objectContaining({
          userName: 'newuser1@user.com',
        }),
      ])
    );
  });

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?