Why does my mock of my api return a 404 error?

Alrighty, round two.

  • Your flushPromises function isn't resolving promises properly when that promise takes some time to respond. The workaround is to return the promise and stick an await in front of it within the .test.js file. Since we're using await on the promise, await flushPromises() isn't needed.
  • In addition, including the headers within the onPost mocked function will cause the function to throw an error. Since you're just mocking this request (and not actually testing its integration), you don't need to include them. However, since you're already using a custom axios configuration anyway, you can just include the headers in the axiosConfig.js file. See the working example of your codesandbox for more information.

As demonstrated in the Unit Testing codesandbox below, if you try to use await flushPromises() on the deleteUserDataOverTime method, it fails. It fails because it didn't resolve the promise. This promise takes some time to resolve and isn't being handled properly.

In addition, due to the asynchronous nature of the tests, you shouldn't include unit and integration tests within the same test file. Since the tests are asynchronous, calling mockAxios.reset() or mockAxios.restore() on the same mocked request or same mocked instance -- to make any additional real or fake API calls -- can and will inadvertently impact all the API calls (again they're asynchronous, not synchronous tests).

Working example of Unit testing an API: https://codesandbox.io/s/6z36z6pzyr (fake API -- includes GET, PUT, POST and DELETE)

Working example of Integration testing an API: https://codesandbox.io/s/7z93xnm206 (real API -- only includes GET, but functionality should remain the same for PUT, POST, and DELETE)

Working example of your codesandbox: https://codesandbox.io/s/526pj28n1n


Okay, this was a tricky one. The issue is on the axios-mock-adapter package. It requires an instance of axios using the .create() method. See here: creating an instance

In your App.js, use:

import axios from "axios";
const instance = axios.create();

instance.post("http://localhost/api/user/update", {name: "Test"}, {headers: {"Authorization": "Bearer token")}});

Nothing needs to be changed in the tests though.

I got the hint from tests of axios-mock-adapter.

An example of such is: post test