Why does my mock of my api return a 404 error?Axios (in React-native) not calling server in localhostGetting 404 error while call oAuth2 api in the browserMock api calls from StorybookAxios keeps sending GET to wrong endpointJest Asynchronous API MockingWhy does Axios get call return a 404 error with basic setup?Mocking API call in JSWhy does my instance of Axios not return the response in a caught error?axios mock can't handle default headers when using jestWhy in React, my axios API call has Authorization Header which contains Bearer <token> but not being authorized and gives 401 error

How to see the previous "Accessed" date in Windows

Hangman Game (YAHG)

Is the use of language other than English 'Reasonable Suspicion' for detention?

Symbol for function composition like a big sum

Designing a time thief proof safe

Is it impolite to ask for an in-flight catalogue with no intention of buying?

Received a package but didn't order it

Research promotions in the middle of post-doc contract

Can anyone put a name to this Circle of Fifths observation?

Where can I find historic TLE?

Do wheelchair aircraft exist?

How 象【しょう】 ( ≈かたち、 すがた、ようす) and 象【ぞう】 (どうぶつ) got to be written with the same kanji?

Is it acceptable to say that a reviewer's concern is not going to be addressed because then the paper would be too long?

Examples of "unsuccessful" theories with afterlives

Averting Bathos

Pi Zero Work With Embedded WIFI And Cellular USB Modem

Why weren't the Death Star plans transmitted electronically?

Lost Update Understanding

Youtube not blocked by iptables

Comma Code - Automate the Boring Stuff with Python

Why are there two fundamental laws of logic?

Is there any relation/leak between two sections of LM358 op-amp?

Subverting the emotional woman and stoic man trope

Why does my browser attempt to download pages from http://clhs.lisp.se instead of viewing them normally?



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


Axios (in React-native) not calling server in localhostGetting 404 error while call oAuth2 api in the browserMock api calls from StorybookAxios keeps sending GET to wrong endpointJest Asynchronous API MockingWhy does Axios get call return a 404 error with basic setup?Mocking API call in JSWhy does my instance of Axios not return the response in a caught error?axios mock can't handle default headers when using jestWhy in React, my axios API call has Authorization Header which contains Bearer <token> but not being authorized and gives 401 error






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








8















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. I have try to remove the header part but the sandbox has just crash when I have run test.



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 = () =>
userMock
.onPost("users", user_resp_full, Utils.getAuth())
.reply(200, data: status: "success");


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

tree.find("#confirm-create").simulate("click");
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
"first_name":"Test","last_name":"Test","email":"test@gmail.com","address":"Test","zipcode":1010,"city":"Test","admin":false
console.log src/Components/Users/UserManage.js:152
POST USER
console.log src/Components/Users/UserManage.js:153
"first_name":"Test","last_name":"Test","email":"test@gmail.com","address":"Test","zipcode":1010,"city":"Test","admin":false




Update



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"));


I have see on axios-mock-adapter github test page that eventually we should put headers in test without the label before:
headers: Autorization: "Bearer token" become Autorization: "Bearer token"

But unfortunately it doesn't work better than I have.



Solution



With the response of Matt Carlotta and his codesandbox, I modify mine with 2 examples of fixed issue:



  • A test of POST request mock using axios*

  • A test of POST request mock using an instance of axios*

* With axios-mock-adapter










share|improve this question


























  • Maybe totally unrelated, but in your testApi function, nothing is returned. In fact I don't see the point of the testApi function, what if you put your userMock.onPost()... directly in your test("something") ?

    – Bernard Pagoaga
    Mar 26 at 13:16











  • Thanks for your comment, I test that but unfortunately doesn't work. I use that function for other mockup of other endpoint and they work.

    – Tutturuuu
    Mar 26 at 14:33











  • have you tried adding a leading slash to your onPost call, '/users' ? the examples all show leading forward slashes, github.com/ctimmerm/axios-mock-adapter

    – N3SS4H
    Mar 26 at 16:20











  • @N3SS4H Yes but I use an axios config that have in baseURL the..base url, like http://localhost:5000/ and I test it but doesn't work.

    – Tutturuuu
    Mar 26 at 16:33


















8















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. I have try to remove the header part but the sandbox has just crash when I have run test.



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 = () =>
userMock
.onPost("users", user_resp_full, Utils.getAuth())
.reply(200, data: status: "success");


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

tree.find("#confirm-create").simulate("click");
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
"first_name":"Test","last_name":"Test","email":"test@gmail.com","address":"Test","zipcode":1010,"city":"Test","admin":false
console.log src/Components/Users/UserManage.js:152
POST USER
console.log src/Components/Users/UserManage.js:153
"first_name":"Test","last_name":"Test","email":"test@gmail.com","address":"Test","zipcode":1010,"city":"Test","admin":false




Update



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"));


I have see on axios-mock-adapter github test page that eventually we should put headers in test without the label before:
headers: Autorization: "Bearer token" become Autorization: "Bearer token"

But unfortunately it doesn't work better than I have.



Solution



With the response of Matt Carlotta and his codesandbox, I modify mine with 2 examples of fixed issue:



  • A test of POST request mock using axios*

  • A test of POST request mock using an instance of axios*

* With axios-mock-adapter










share|improve this question


























  • Maybe totally unrelated, but in your testApi function, nothing is returned. In fact I don't see the point of the testApi function, what if you put your userMock.onPost()... directly in your test("something") ?

    – Bernard Pagoaga
    Mar 26 at 13:16











  • Thanks for your comment, I test that but unfortunately doesn't work. I use that function for other mockup of other endpoint and they work.

    – Tutturuuu
    Mar 26 at 14:33











  • have you tried adding a leading slash to your onPost call, '/users' ? the examples all show leading forward slashes, github.com/ctimmerm/axios-mock-adapter

    – N3SS4H
    Mar 26 at 16:20











  • @N3SS4H Yes but I use an axios config that have in baseURL the..base url, like http://localhost:5000/ and I test it but doesn't work.

    – Tutturuuu
    Mar 26 at 16:33














8












8








8








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. I have try to remove the header part but the sandbox has just crash when I have run test.



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 = () =>
userMock
.onPost("users", user_resp_full, Utils.getAuth())
.reply(200, data: status: "success");


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

tree.find("#confirm-create").simulate("click");
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
"first_name":"Test","last_name":"Test","email":"test@gmail.com","address":"Test","zipcode":1010,"city":"Test","admin":false
console.log src/Components/Users/UserManage.js:152
POST USER
console.log src/Components/Users/UserManage.js:153
"first_name":"Test","last_name":"Test","email":"test@gmail.com","address":"Test","zipcode":1010,"city":"Test","admin":false




Update



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"));


I have see on axios-mock-adapter github test page that eventually we should put headers in test without the label before:
headers: Autorization: "Bearer token" become Autorization: "Bearer token"

But unfortunately it doesn't work better than I have.



Solution



With the response of Matt Carlotta and his codesandbox, I modify mine with 2 examples of fixed issue:



  • A test of POST request mock using axios*

  • A test of POST request mock using an instance of axios*

* With axios-mock-adapter










share|improve this question
















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. I have try to remove the header part but the sandbox has just crash when I have run test.



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 = () =>
userMock
.onPost("users", user_resp_full, Utils.getAuth())
.reply(200, data: status: "success");


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

tree.find("#confirm-create").simulate("click");
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
"first_name":"Test","last_name":"Test","email":"test@gmail.com","address":"Test","zipcode":1010,"city":"Test","admin":false
console.log src/Components/Users/UserManage.js:152
POST USER
console.log src/Components/Users/UserManage.js:153
"first_name":"Test","last_name":"Test","email":"test@gmail.com","address":"Test","zipcode":1010,"city":"Test","admin":false




Update



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"));


I have see on axios-mock-adapter github test page that eventually we should put headers in test without the label before:
headers: Autorization: "Bearer token" become Autorization: "Bearer token"

But unfortunately it doesn't work better than I have.



Solution



With the response of Matt Carlotta and his codesandbox, I modify mine with 2 examples of fixed issue:



  • A test of POST request mock using axios*

  • A test of POST request mock using an instance of axios*

* With axios-mock-adapter







reactjs jestjs axios enzyme axios-mock-adapter






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 1 at 9:32







Tutturuuu

















asked Mar 26 at 10:46









TutturuuuTutturuuu

2523 silver badges23 bronze badges




2523 silver badges23 bronze badges















  • Maybe totally unrelated, but in your testApi function, nothing is returned. In fact I don't see the point of the testApi function, what if you put your userMock.onPost()... directly in your test("something") ?

    – Bernard Pagoaga
    Mar 26 at 13:16











  • Thanks for your comment, I test that but unfortunately doesn't work. I use that function for other mockup of other endpoint and they work.

    – Tutturuuu
    Mar 26 at 14:33











  • have you tried adding a leading slash to your onPost call, '/users' ? the examples all show leading forward slashes, github.com/ctimmerm/axios-mock-adapter

    – N3SS4H
    Mar 26 at 16:20











  • @N3SS4H Yes but I use an axios config that have in baseURL the..base url, like http://localhost:5000/ and I test it but doesn't work.

    – Tutturuuu
    Mar 26 at 16:33


















  • Maybe totally unrelated, but in your testApi function, nothing is returned. In fact I don't see the point of the testApi function, what if you put your userMock.onPost()... directly in your test("something") ?

    – Bernard Pagoaga
    Mar 26 at 13:16











  • Thanks for your comment, I test that but unfortunately doesn't work. I use that function for other mockup of other endpoint and they work.

    – Tutturuuu
    Mar 26 at 14:33











  • have you tried adding a leading slash to your onPost call, '/users' ? the examples all show leading forward slashes, github.com/ctimmerm/axios-mock-adapter

    – N3SS4H
    Mar 26 at 16:20











  • @N3SS4H Yes but I use an axios config that have in baseURL the..base url, like http://localhost:5000/ and I test it but doesn't work.

    – Tutturuuu
    Mar 26 at 16:33

















Maybe totally unrelated, but in your testApi function, nothing is returned. In fact I don't see the point of the testApi function, what if you put your userMock.onPost()... directly in your test("something") ?

– Bernard Pagoaga
Mar 26 at 13:16





Maybe totally unrelated, but in your testApi function, nothing is returned. In fact I don't see the point of the testApi function, what if you put your userMock.onPost()... directly in your test("something") ?

– Bernard Pagoaga
Mar 26 at 13:16













Thanks for your comment, I test that but unfortunately doesn't work. I use that function for other mockup of other endpoint and they work.

– Tutturuuu
Mar 26 at 14:33





Thanks for your comment, I test that but unfortunately doesn't work. I use that function for other mockup of other endpoint and they work.

– Tutturuuu
Mar 26 at 14:33













have you tried adding a leading slash to your onPost call, '/users' ? the examples all show leading forward slashes, github.com/ctimmerm/axios-mock-adapter

– N3SS4H
Mar 26 at 16:20





have you tried adding a leading slash to your onPost call, '/users' ? the examples all show leading forward slashes, github.com/ctimmerm/axios-mock-adapter

– N3SS4H
Mar 26 at 16:20













@N3SS4H Yes but I use an axios config that have in baseURL the..base url, like http://localhost:5000/ and I test it but doesn't work.

– Tutturuuu
Mar 26 at 16:33






@N3SS4H Yes but I use an axios config that have in baseURL the..base url, like http://localhost:5000/ and I test it but doesn't work.

– Tutturuuu
Mar 26 at 16:33













2 Answers
2






active

oldest

votes


















4







+100









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






share|improve this answer



























  • Your response doesn't real help me for my issue, you describe test with GET request but no one about a POST request with header that can be the error. I will however create a test who can be reproduce.

    – Tutturuuu
    Mar 28 at 16:58











  • Yes it matter because my GET request (The same in your test) in my test works perfectly but it wasn't the case with my POST request which all failed. So I search why the POST request failed but I'm going to create a sandbox test with that.

    – Tutturuuu
    Mar 28 at 17:04











  • I have add a sandbox link.

    – Tutturuuu
    Mar 28 at 17:36











  • Please read carefully: An API implementation test (aka Unit Test) will mimic the request, the side effect and the result. An API integration test (aka End to End Test) will actually test the request, the side effect and the result from client to API. I've also updated my answer above to highlight the differences.

    – Matt Carlotta
    Mar 28 at 19:03












  • Pretty sure I figured out your problem. See the updated answer above.

    – Matt Carlotta
    Mar 29 at 21:19


















2
















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






share|improve this answer

























  • Like on github of axios-mock-adapter, I send you the CodeSandbox updated with your solution but it doesn't work. Furthermore, my issue use already an instance of axios with custom config and doesn't work too.

    – Tutturuuu
    Mar 29 at 16:33













Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);














draft saved

draft discarded
















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55355254%2fwhy-does-my-mock-of-my-api-return-a-404-error%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









4







+100









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






share|improve this answer



























  • Your response doesn't real help me for my issue, you describe test with GET request but no one about a POST request with header that can be the error. I will however create a test who can be reproduce.

    – Tutturuuu
    Mar 28 at 16:58











  • Yes it matter because my GET request (The same in your test) in my test works perfectly but it wasn't the case with my POST request which all failed. So I search why the POST request failed but I'm going to create a sandbox test with that.

    – Tutturuuu
    Mar 28 at 17:04











  • I have add a sandbox link.

    – Tutturuuu
    Mar 28 at 17:36











  • Please read carefully: An API implementation test (aka Unit Test) will mimic the request, the side effect and the result. An API integration test (aka End to End Test) will actually test the request, the side effect and the result from client to API. I've also updated my answer above to highlight the differences.

    – Matt Carlotta
    Mar 28 at 19:03












  • Pretty sure I figured out your problem. See the updated answer above.

    – Matt Carlotta
    Mar 29 at 21:19















4







+100









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






share|improve this answer



























  • Your response doesn't real help me for my issue, you describe test with GET request but no one about a POST request with header that can be the error. I will however create a test who can be reproduce.

    – Tutturuuu
    Mar 28 at 16:58











  • Yes it matter because my GET request (The same in your test) in my test works perfectly but it wasn't the case with my POST request which all failed. So I search why the POST request failed but I'm going to create a sandbox test with that.

    – Tutturuuu
    Mar 28 at 17:04











  • I have add a sandbox link.

    – Tutturuuu
    Mar 28 at 17:36











  • Please read carefully: An API implementation test (aka Unit Test) will mimic the request, the side effect and the result. An API integration test (aka End to End Test) will actually test the request, the side effect and the result from client to API. I've also updated my answer above to highlight the differences.

    – Matt Carlotta
    Mar 28 at 19:03












  • Pretty sure I figured out your problem. See the updated answer above.

    – Matt Carlotta
    Mar 29 at 21:19













4







+100







4







+100



4






+100





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






share|improve this answer















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







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 30 at 1:45

























answered Mar 28 at 16:46









Matt CarlottaMatt Carlotta

5,8842 gold badges8 silver badges17 bronze badges




5,8842 gold badges8 silver badges17 bronze badges















  • Your response doesn't real help me for my issue, you describe test with GET request but no one about a POST request with header that can be the error. I will however create a test who can be reproduce.

    – Tutturuuu
    Mar 28 at 16:58











  • Yes it matter because my GET request (The same in your test) in my test works perfectly but it wasn't the case with my POST request which all failed. So I search why the POST request failed but I'm going to create a sandbox test with that.

    – Tutturuuu
    Mar 28 at 17:04











  • I have add a sandbox link.

    – Tutturuuu
    Mar 28 at 17:36











  • Please read carefully: An API implementation test (aka Unit Test) will mimic the request, the side effect and the result. An API integration test (aka End to End Test) will actually test the request, the side effect and the result from client to API. I've also updated my answer above to highlight the differences.

    – Matt Carlotta
    Mar 28 at 19:03












  • Pretty sure I figured out your problem. See the updated answer above.

    – Matt Carlotta
    Mar 29 at 21:19

















  • Your response doesn't real help me for my issue, you describe test with GET request but no one about a POST request with header that can be the error. I will however create a test who can be reproduce.

    – Tutturuuu
    Mar 28 at 16:58











  • Yes it matter because my GET request (The same in your test) in my test works perfectly but it wasn't the case with my POST request which all failed. So I search why the POST request failed but I'm going to create a sandbox test with that.

    – Tutturuuu
    Mar 28 at 17:04











  • I have add a sandbox link.

    – Tutturuuu
    Mar 28 at 17:36











  • Please read carefully: An API implementation test (aka Unit Test) will mimic the request, the side effect and the result. An API integration test (aka End to End Test) will actually test the request, the side effect and the result from client to API. I've also updated my answer above to highlight the differences.

    – Matt Carlotta
    Mar 28 at 19:03












  • Pretty sure I figured out your problem. See the updated answer above.

    – Matt Carlotta
    Mar 29 at 21:19
















Your response doesn't real help me for my issue, you describe test with GET request but no one about a POST request with header that can be the error. I will however create a test who can be reproduce.

– Tutturuuu
Mar 28 at 16:58





Your response doesn't real help me for my issue, you describe test with GET request but no one about a POST request with header that can be the error. I will however create a test who can be reproduce.

– Tutturuuu
Mar 28 at 16:58













Yes it matter because my GET request (The same in your test) in my test works perfectly but it wasn't the case with my POST request which all failed. So I search why the POST request failed but I'm going to create a sandbox test with that.

– Tutturuuu
Mar 28 at 17:04





Yes it matter because my GET request (The same in your test) in my test works perfectly but it wasn't the case with my POST request which all failed. So I search why the POST request failed but I'm going to create a sandbox test with that.

– Tutturuuu
Mar 28 at 17:04













I have add a sandbox link.

– Tutturuuu
Mar 28 at 17:36





I have add a sandbox link.

– Tutturuuu
Mar 28 at 17:36













Please read carefully: An API implementation test (aka Unit Test) will mimic the request, the side effect and the result. An API integration test (aka End to End Test) will actually test the request, the side effect and the result from client to API. I've also updated my answer above to highlight the differences.

– Matt Carlotta
Mar 28 at 19:03






Please read carefully: An API implementation test (aka Unit Test) will mimic the request, the side effect and the result. An API integration test (aka End to End Test) will actually test the request, the side effect and the result from client to API. I've also updated my answer above to highlight the differences.

– Matt Carlotta
Mar 28 at 19:03














Pretty sure I figured out your problem. See the updated answer above.

– Matt Carlotta
Mar 29 at 21:19





Pretty sure I figured out your problem. See the updated answer above.

– Matt Carlotta
Mar 29 at 21:19













2
















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






share|improve this answer

























  • Like on github of axios-mock-adapter, I send you the CodeSandbox updated with your solution but it doesn't work. Furthermore, my issue use already an instance of axios with custom config and doesn't work too.

    – Tutturuuu
    Mar 29 at 16:33















2
















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






share|improve this answer

























  • Like on github of axios-mock-adapter, I send you the CodeSandbox updated with your solution but it doesn't work. Furthermore, my issue use already an instance of axios with custom config and doesn't work too.

    – Tutturuuu
    Mar 29 at 16:33













2














2










2









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






share|improve this answer













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







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 29 at 15:39









aitchkhanaitchkhan

5945 silver badges24 bronze badges




5945 silver badges24 bronze badges















  • Like on github of axios-mock-adapter, I send you the CodeSandbox updated with your solution but it doesn't work. Furthermore, my issue use already an instance of axios with custom config and doesn't work too.

    – Tutturuuu
    Mar 29 at 16:33

















  • Like on github of axios-mock-adapter, I send you the CodeSandbox updated with your solution but it doesn't work. Furthermore, my issue use already an instance of axios with custom config and doesn't work too.

    – Tutturuuu
    Mar 29 at 16:33
















Like on github of axios-mock-adapter, I send you the CodeSandbox updated with your solution but it doesn't work. Furthermore, my issue use already an instance of axios with custom config and doesn't work too.

– Tutturuuu
Mar 29 at 16:33





Like on github of axios-mock-adapter, I send you the CodeSandbox updated with your solution but it doesn't work. Furthermore, my issue use already an instance of axios with custom config and doesn't work too.

– Tutturuuu
Mar 29 at 16:33


















draft saved

draft discarded















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55355254%2fwhy-does-my-mock-of-my-api-return-a-404-error%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript