#StackBounty: #reactjs #jestjs #axios #enzyme #axios-mock-adapter Why my mock of my api return a 404 error?

Bounty: 100

I use axios-mock-adapter to mock my API, it works correctly but on one mock it returns a 404 error and I cannot found why.

There is here the sandbox with test, you can see when we run the test, the second check failed because the axios POST call haven’t be mock.

Mock of API (test part):

import axios from "axios";
import MockAdapter from 'axios-mock-adapter';
import Utils from "../Utils/Utils";

// Global variable for post request with axios
global.users_post = axios.create({
  baseURL: "http://localhost:5000/api/",
  headers: {'Content-Type': 'application/json'}

/* Mockup API */
var userMock = new MockAdapter(users_post);

const user_resp_full = {
  data: {
    first_name: "Test",
    last_name: "Test",
    email: "test@gmail.com",
    address: "Test",
    zipcode: 1010,
    city: "Test",
    admin: false

const testAPI = () => {
      .onPost("users", user_resp_full, Utils.getAuth())
      .reply(200, {data: {status: "success"}});

test("something", async () => {
  let tree = shallow(<UserManage type="create" uuid="" />);
  await flushPromises();
  // Some test

  await flushPromises();
  // Error 404, mock isn't trigger

I have already check, data is the same, same for endpoint but it seems doesn’t mock it correctly.

Axios call in class:

function (fields) {
    users_post.post("users", fields, Utils.getAuth())
    .then(resp => {
      let data = resp.data;
      // Do something
    .catch(resp => {
      let data = resp.response.data;
      // Display error

At this point, in my Jest test it returns a 404 error, so it hasn’t mock my endpoint API (Other works).
The Utils.getAuth() function returns a header with a auth token.

Data send

That concerns content of data send (First is before the test call with mock, second is in the tested function and data log is the data send to api):

    console.log src/tests/UserManage.test.js:222
      POST USER 2
    console.log src/Components/Users/UserManage.js:152
    console.log src/Components/Users/UserManage.js:153


This error happen only when I use a POST request with a header like that:

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

Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.