-
Notifications
You must be signed in to change notification settings - Fork 248
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Mock failed with 404 Error #116
Comments
I can't do much with the little information that you're giving, but likely the code that adds the mock handlers does not get run when running a single test. |
I got a similar error to @kirankbs. My code seems to not evaluate the axios.get bit with mock Here is a sample of my code export const getLocationInfo = (lat, lng) => {
return ((dispatch) => {
return axios.get(process.env.API_LOCATION_URL+`/json?latlng=${lat},${lng}&key=${process.env.GOOGLE_KEY}`)
.then((response) => {
dispatch({ type: "FETCHED_LOCATION_INFO", payload: response.data.results });
}).catch((error) => {
dispatch({ type: 'FAILED_FETCHING_LOCATION_INFO', payload: error });
});
});
}; The test code below it('should dispatch FETCHED_LOCATION_INFO when getLocationInfo completes successfully', (done) => {
let middlewares = [thunk];
let mockStore = configureMockStore(middlewares);
let store = mockStore({});
mock = new MockAdapter(axios);
mock.onGet('http://maps.google.com/').reply(200, {
data: {
results: [
{
formatted_address: 'Abc Rd, City, Country'
}
]
}
});
store.dispatch(getLocationInfo(-5.2177265, 12.9889)).then(() => {
const actualActions = store.getActions();
expect(expectedActions[0].type).toEqual(actualActions[0].type);
done();
});
}); This is my error
|
Getting the same error as mentioned above mock = new MockAdapter(requestInstance)
mock.onPost(`${SERVER_URL}/api/cart`).reply(200, 'cart')
mock.onGet(`${SERVER_URL}/api/quoteDetails/product/`).reply(200, { data: {x: 2} }) |
@djalmaaraujo What does your http request look like for POST and GET? |
@davidlewallen Not sure if I understood the question. |
@djalmaaraujo can you show me the code that is making the request to |
/**
* Axios Request Instance (Move to config later)
*/
export const requestInstance = axios.create({
baseURL: SERVER_URL,
timeout: 20000,
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }
}) /**
* Fetch QuoteDetails using ISBN
*/
export const buybackFetchQuoteDetails = (isbn) => {
return (dispatch) => {
if (!isbn) {
return dispatch({
type: 'BUYBACK/quoteDetailsFail',
payload: 'Invalid ISBN, please try another ISBN.'
})
}
dispatch({
type: 'BUYBACK/loading'
})
return createOrReturnCart().then((cart) => {
dispatch({
type: 'BUYBACK/createOrReturnCart',
payload: cart
})
return requestInstance.get(`api/quoteDetails/product/${isbn}`)
.then((response) => {
dispatch({
type: 'BUYBACK/quoteDetailsSuccess',
payload: response.data
})
})
.catch((error) => {
console.log('I ALWAYS GET CATCH HERE')
dispatch({
type: 'BUYBACK/quoteDetailsFail',
payload: (error.response.data && error.response.data.error) ? error.response.data.error : 'Invalid ISBN, please try another ISBN.'
})
return error
})
})
}
} export const createOrReturnCart = () => {
return requestInstance.post('api/cart')
.then((response) => response.data)
.catch(err => err)
} Spec: describe('async quote details', () => {
let mock;
let dispatchMockSpy;
beforeEach(() => {
mock = new MockAdapter(requestInstance)
dispatchMockSpy = sinon.spy()
mock
.onPost(`${SERVER_URL}/api/cart`).reply(200, 'cart')
.onGet(`${SERVER_URL}/api/quoteDetails/product/123456`).reply(200, 'quoteDetailsData')
})
afterEach(() => {
mock.reset()
})
it("should dispatch data", () => {
const buybackFetchQuoteDetailsMock = buybackFetchQuoteDetails('123456')
buybackFetchQuoteDetailsMock(dispatchMockSpy).then((x) => {
expect(dispatchMockSpy.calledWith({
type: 'BUYBACK/loading'
})).toBeTruthy()
expect(dispatchMockSpy.calledWith({
type: 'BUYBACK/createOrReturnCart',
payload: 'cart'
})).toBeTruthy()
}).catch((x) => console.log(x))
})
}) |
@djalmaaraujo the code you link has no GET request to |
@davidlewallen I updated the code above, please take a look. Just added what is |
@djalmaaraujo I think its how you are using the base url. You can I just mocked this up and it works just fine isolated from Redux.
|
@davidlewallen But why the /api/cart works and the other don't? |
I just console.log requestInstance ● Console
console.log src/Actions/BuyBackActions.test.js:49
{ [Function: wrap]
request: [Function: wrap],
delete: [Function: wrap],
get: [Function: wrap],
head: [Function: wrap],
options: [Function: wrap],
post: [Function: wrap],
put: [Function: wrap],
patch: [Function: wrap],
defaults:
{ adapter: [Function: xhrAdapter],
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 20000,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
headers:
{ common: [Object],
delete: {},
get: {},
head: {},
post: [Object],
put: [Object],
patch: [Object],
Accept: 'application/json',
'Content-Type': 'application/json' },
baseURL: 'http://localhost:8080/buyback' },
interceptors:
{ request: InterceptorManager { handlers: [] },
response: InterceptorManager { handlers: [] } } }
console.log src/Actions/BuyBackActions.js:46 |
@djalmaaraujo add |
● Console
console.log src/Actions/BuyBackActions.test.js:59
{
"get": [
[
"http://localhost:8080/buyback/api/quoteDetails/product/123456",
null,
200,
"quoteDetailsData",
null
]
],
"post": [
[
"http://localhost:8080/buyback/api/cart",
null,
200,
"cart",
null
]
],
"head": [],
"delete": [],
"patch": [],
"put": []
} I was using onAny, just fixed. see now |
@davidlewallen The error returned in the { Error: Request failed with status code 404
at createErrorResponse (/Users/cooper/dev/valore/valore-buyback-webapp/client/node_modules/axios-mock-adapter/src/utils.js:110:15)
at Object.settle (/Users/cooper/dev/valore/valore-buyback-webapp/client/node_modules/axios-mock-adapter/src/utils.js:90:16)
at handleRequest (/Users/cooper/dev/valore/valore-buyback-webapp/client/node_modules/axios-mock-adapter/src/handle_request.js:55:11)
at /Users/cooper/dev/valore/valore-buyback-webapp/client/node_modules/axios-mock-adapter/src/index.js:16:9
at new Promise (<anonymous>)
at MockAdapter.<anonymous> (/Users/cooper/dev/valore/valore-buyback-webapp/client/node_modules/axios-mock-adapter/src/index.js:15:14)
at dispatchRequest (/Users/cooper/dev/valore/valore-buyback-webapp/client/node_modules/axios/lib/core/dispatchRequest.js:59:10)
at <anonymous>
config:
{ adapter: null,
transformRequest: { '0': [Function: transformRequest] },
transformResponse: { '0': [Function: transformResponse] },
timeout: 20000,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
headers:
{ Accept: 'application/json',
'Content-Type': 'application/json' },
baseURL: 'http://localhost:8080/buyback',
method: 'get',
url: '/api/quoteDetails/product/123456',
data: undefined },
response:
{ status: 404,
config:
{ adapter: null,
transformRequest: [Object],
transformResponse: [Object],
timeout: 20000,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
headers: [Object],
baseURL: 'http://localhost:8080/buyback',
method: 'get',
url: '/api/quoteDetails/product/123456',
data: undefined },
data: undefined } } |
@djalmaaraujo try removing the |
@davidlewallen Same thing. Still have the /api/cart working, but not the other request. The difference is that this request is inside another promise. maybe that's the reason? |
@djalmaaraujo hmm I am seeing something a little different on my end. Try adding this to
And see if you get an error there? |
@davidlewallen I changed a little bit the code to show you the test results: /**
* Fetch QuoteDetails using ISBN
*/
export const buybackFetchQuoteDetails = (isbn) => {
return (dispatch) => {
if (!isbn) {
return dispatch({
type: 'BUYBACK/quoteDetailsFail',
payload: 'Invalid ISBN, please try another ISBN.'
})
}
dispatch({
type: 'BUYBACK/loading'
})
return createOrReturnCart().then((cart) => {
console.log('CART PASSED')
dispatch({
type: 'BUYBACK/createOrReturnCart',
payload: cart
})
return requestInstance.get(`api/quoteDetails/product/${isbn}`)
.then((response) => {
console.log('QUOTE DETAILS RESOLVED')
dispatch({
type: 'BUYBACK/quoteDetailsSuccess',
payload: response.data
})
})
.catch((error) => {
console.log('ERROR IN QUOTE DETAILS')
dispatch({
type: 'BUYBACK/quoteDetailsFail',
payload: (error.response.data && error.response.data.error) ? error.response.data.error : 'Invalid ISBN, please try another ISBN.'
})
return error
})
})
}
}
const createOrReturnCart = () => requestInstance.post('/api/cart')
.then(response => response)
.catch((error) => {
console.log('error', error)
return error;
}) SPEC: PASS src/Containers/BuyBackContainer/BuyBackContainer.test.js
PASS src/Actions/BuyBackActions.test.js
● Console
console.log src/Actions/BuyBackActions.js:32
CART PASSED
console.log src/Actions/BuyBackActions.js:47
ERROR IN QUOTE DETAILS
console.log src/Actions/BuyBackActions.test.js:81
{ Error: expect(received).toBeTruthy()
Expected value to be truthy, instead received
false
at buybackFetchQuoteDetailsMock.then.x (/Users/cooper/dev/valore/valore-buyback-webapp/client/src/Actions/BuyBackActions.test.js:75:11)
at <anonymous> matcherResult: { message: [Function], pass: false } }
Test Suites: 2 passed, 2 total
Tests: 6 passed, 6 total
Snapshots: 0 total
Time: 0.938s, estimated 1s
Ran all test suites related to changed files.
Watch Usage: Press w to show more. |
@djalmaaraujo One last thing before I give up.
See if that give any better results |
@davidlewallen Sorry the delay, but still failing. I will give up, check for another alternative. Thanks for your time, honestly. |
@davidlewallen I was able to make it work. I split the method into 2 methods and tested separately. I can't tell you exactly what is the issue, but I believe it's a bug from this mock-adapter, when you have a nested promise level, it's like the mock is not aware of that request. |
@davidlewallen After another time facing the same issue, I think the solution is to pass (done) and wait for the correct ajax to finish. Check this example, and it works:
In this case, I am always getting 404 for the /api/cart... but with the done, now it works. |
Hi, I'm not able to get it to work even with @djalmaaraujo's solution using the What could be missing here? Dependencies: The method under test:
The test:
The error:
|
+1 I'm using axios in a node service layer that utilizes |
Getting exactly the same issue with a nested promise. |
After debugging session focused on The functions used within |
What version of node are people using? I am also facing the same issue and I believe I have chased it down to My environment:
To demonstrate the issue, go into your node_modules and update your function find(array, predicate) {
var length = array.length;
for (var i = 0; i < length; i++) {
var value = array[i];
const pred = predicate(value);
if (pred) return value;
else console.log(`Failed to match value: ${pred}`);
}
}
// ...
function isBodyOrParametersMatching(method, body, parameters, required) {
console.log('isBodyOrParametersMatching');
// ... What you'll see is that the predicate fails to match with a log statement of: My theory is that there is a bug in the way V8 handles [arbitrarily] complex bitwise statements. I've seen this behavior (where it returns undefined instead of a boolean) in another of our internal projects (completely unrelated to Once you confirmed the behavior above, try replacing the function findHandler(handlers, method, url, body, parameters, headers, baseURL) {
console.log(arguments);
console.log(handlers);
return find(handlers[method.toLowerCase()], function(handler) {
let urlMatch = false;
if (typeof handler[0] === 'string') {
urlMatch = isUrlMatching(url, handler[0]) || isUrlMatching(combineUrls(baseURL, url), handler[0]);
} else if (handler[0] instanceof RegExp) {
urlMatch = handler[0].test(url) || handler[0].test(combineUrls(baseURL, url));
}
const bodyParamMatch = urlMatch && isBodyOrParametersMatching(method, body, parameters, handler[1]);
const headersMatch = bodyParamMatch && isRequestHeadersMatching(headers, handler[2]);
return headersMatch
});
} You'll notice that My theory is that there is a bug in the way the V8 runtime parse boolean statements. Specifically, when the V8 runtime parses a bitwise boolean statement where there is a parentheses group followed by a method invocation. For whatever reason, I believe V8 falls on its face and returns As I said earlier, I've seen this in an internal ReactJS app (which was not using axios) running in the latest Chrome browser. I'll see if I can put together a sample app to test my theory. I'll also put together a PR to solve this issue (with the updated PS.- If someone else wants to take the code above and create a PR before I do, please feel free. (Just make sure to reference this issue) |
in my case running |
Hi! I have same issue - I have two tests in describe block and each of them runs perfectly, but running both of them leads to fail. My current approach is: _axiosMockAdapter.js:
test.js:
Actually, it seems to me i tried all of the methods in this discussion - i used axios strictly from package, i imported it from other file (now i use this method), I tried to reset it on each iteration - didn't help either:
Even run |
Aside from only exporting one mock instance, I've also been bitten in the butt when I use the spread operator in the body and the object contains extra fields than expected. Just wanted to share. I really wish we'd see some error a la: |
I'm having the same error. I tried the following: adapter.onPost(`${baseUrl}/endpoint`).reply(config => {
console.log('config', config);
return [200];
}); This return the 404 error: But dropping the url matcher works: adapter.onPost().reply(config => {
console.log('config', config);
return [200];
}); Note that |
Normally we'd be mocking the web client library, but the two libraries I've tried are not reliable. axios-mock-adapter simply doesn't work with it succumbing to this issue: ctimmerm/axios-mock-adapter#116 (comment) Tried everything there, no success. Moxios, is the one I've first chosen and used in previous commits. It's older, not updated in years and more problematic is that it's prone to "heisenbugs", i.e: randomly breaking for no obvious reason. I haven't tried jasmine-ajax, but I figured it's much more time-effective and reliable to fake the API instead (we are talking about unit tests here, so they should be isolated from the real implementation). Bonus point is that we can use the fake API to test and prototype API endpoints with sample data before implementing for real (and thus being able to try multiple designs). In the future, we should revisiting the async mocking libraries as that's the long-term proper practice.
Normally we'd be mocking the web client library, but the two libraries I've tried are not reliable. axios-mock-adapter simply doesn't work with it succumbing to this issue: ctimmerm/axios-mock-adapter#116 (comment) Tried everything there, no success. Moxios, is the one I've first chosen and used in previous commits. It's older, not updated in years and more problematic is that it's prone to "heisenbugs", i.e: randomly breaking for no obvious reason. I haven't tried jasmine-ajax, but I figured it's much more time-effective and reliable to fake the API instead (we are talking about unit tests here, so they should be isolated from the real implementation). Bonus point is that we can use the fake API to test and prototype API endpoints with sample data before implementing for real (and thus being able to try multiple designs). In the future, we should revisiting the async mocking libraries as that's the long-term proper practice.
Normally we'd be mocking the web client library, but the two libraries I've tried are not reliable. axios-mock-adapter simply doesn't work with it succumbing to this issue: ctimmerm/axios-mock-adapter#116 (comment) Tried everything there, no success. Moxios, is the one I've first chosen and used in previous commits. It's older, not updated in years and more problematic is that it's prone to "heisenbugs", i.e: randomly breaking for no obvious reason. I haven't tried jasmine-ajax, but I figured it's much more time-effective and reliable to fake the API instead (we are talking about unit tests here, so they should be isolated from the real implementation). Bonus point is that we can use the fake API to test and prototype API endpoints with sample data before implementing for real (and thus being able to try multiple designs). In the future, we should revisiting the async mocking libraries as that's the long-term proper practice.
Normally we'd be mocking the web client library, but the two libraries I've tried are not reliable. axios-mock-adapter simply doesn't work with it succumbing to this issue: ctimmerm/axios-mock-adapter#116 (comment) Tried everything there, no success. Moxios, is the one I've first chosen and used in previous commits. It's older, not updated in years and more problematic is that it's prone to "heisenbugs", i.e: randomly breaking for no obvious reason. I haven't tried jasmine-ajax, but I figured it's much more time-effective and reliable to fake the API instead (we are talking about unit tests here, so they should be isolated from the real implementation). Bonus point is that we can use the fake API to test and prototype API endpoints with sample data before implementing for real (and thus being able to try multiple designs). In the future, we should revisiting the async mocking libraries as that's the long-term proper practice.
Normally we'd be mocking the web client library, but the two libraries I've tried are not reliable. axios-mock-adapter simply doesn't work with it succumbing to this issue: ctimmerm/axios-mock-adapter#116 (comment) Tried everything there, no success. Moxios, is the one I've first chosen and used in previous commits. It's older, not updated in years and more problematic is that it's prone to "heisenbugs", i.e: randomly breaking for no obvious reason. I haven't tried jasmine-ajax, but I figured it's much more time-effective and reliable to fake the API instead (we are talking about unit tests here, so they should be isolated from the real implementation). Bonus point is that we can use the fake API to test and prototype API endpoints with sample data before implementing for real (and thus being able to try multiple designs). In the future, we should revisiting the async mocking libraries as that's the long-term proper practice.
Normally we'd be mocking the web client library, but the two libraries I've tried are not reliable. axios-mock-adapter simply doesn't work with it succumbing to this issue: ctimmerm/axios-mock-adapter#116 (comment) Tried everything there, no success. Moxios, is the one I've first chosen and used in previous commits. It's older, not updated in years and more problematic is that it's prone to "heisenbugs", i.e: randomly breaking for no obvious reason. I haven't tried jasmine-ajax, but I figured it's much more time-effective and reliable to fake the API instead (we are talking about unit tests here, so they should be isolated from the real implementation). Bonus point is that we can use the fake API to test and prototype API endpoints with sample data before implementing for real (and thus being able to try multiple designs). In the future, we should revisiting the async mocking libraries as that's the long-term proper practice.
I spent awhile on a bug today where we had accidentally passed in incorrect data in an Is there anyway that we could get more output for this situation? Like "Hi you sent me this payload, header, url, etc but that doesn't match anything you've set up for me." If being extra ambitious, we could show them the closes matches to the config MockAdapter received. I'd be happy to help with this, but I just naively felt like I want to put console logs in the Here is a code sample that illustrates the situation: Test Setup Code import axios from 'axios'
const mockAdapter = new MockAdapter(axios)
mockAdapter.onPost('/api/my-url', {
something: [
{
i: "hope",
that: "this",
matches: "whoops-typo"
}
]
}).replyOnce(200) App Code await axios
.post('/api/my-url/', {
something: [
{
i: "hope",
that: "this",
matches: "but-it-wont"
}
]
}) Resulting Message
Potential Desired Message
Thank you for reading this far. I apologize if this is not the thread to have posted this request. I am happy to make a new issue. Again, I would consider helping out if I had the guidance for what you would prefer. |
@Jackman3005: The default behavior of the mock adapter is to return a 404 when a request can't be matched to a handler. The reason for this is that it's not possible to know whether the lack of a match was intentional or a mistake. You can change this to throw an exception when no match is found: new MockAdapter(axiosInstance, { onNoMatch: "throwException" }); Could you check if that would work for you and if there's something we can still improve there? |
Weirdly enough, this was the fix to my problem. Alll I had to do was to pass |
Normally we'd be mocking the web client library, but the two libraries I've tried are not reliable. axios-mock-adapter simply doesn't work with it succumbing to this issue: ctimmerm/axios-mock-adapter#116 (comment) Tried everything there, no success. Moxios, is the one I've first chosen and used in previous commits. It's older, not updated in years and more problematic is that it's prone to "heisenbugs", i.e: randomly breaking for no obvious reason. I haven't tried jasmine-ajax, but I figured it's much more time-effective and reliable to fake the API instead (we are talking about unit tests here, so they should be isolated from the real implementation). Bonus point is that we can use the fake API to test and prototype API endpoints with sample data before implementing for real (and thus being able to try multiple designs). In the future, we should revisiting the async mocking libraries as that's the long-term proper practice.
Normally we'd be mocking the web client library, but the two libraries I've tried are not reliable. axios-mock-adapter simply doesn't work with it succumbing to this issue: ctimmerm/axios-mock-adapter#116 (comment) Tried everything there, no success. Moxios, is the one I've first chosen and used in previous commits. It's older, not updated in years and more problematic is that it's prone to "heisenbugs", i.e: randomly breaking for no obvious reason. I haven't tried jasmine-ajax, but I figured it's much more time-effective and reliable to fake the API instead (we are talking about unit tests here, so they should be isolated from the real implementation). Bonus point is that we can use the fake API to test and prototype API endpoints with sample data before implementing for real (and thus being able to try multiple designs). In the future, we should revisiting the async mocking libraries as that's the long-term proper practice.
Normally we'd be mocking the web client library, but the two libraries I've tried are not reliable. axios-mock-adapter simply doesn't work with it succumbing to this issue: ctimmerm/axios-mock-adapter#116 (comment) Tried everything there, no success. Moxios, is the one I've first chosen and used in previous commits. It's older, not updated in years and more problematic is that it's prone to "heisenbugs", i.e: randomly breaking for no obvious reason. I haven't tried jasmine-ajax, but I figured it's much more time-effective and reliable to fake the API instead (we are talking about unit tests here, so they should be isolated from the real implementation). Bonus point is that we can use the fake API to test and prototype API endpoints with sample data before implementing for real (and thus being able to try multiple designs). In the future, we should revisiting the async mocking libraries as that's the long-term proper practice.
I was getting the same error |
Normally we'd be mocking the web client library, but the two libraries I've tried are not reliable. axios-mock-adapter simply doesn't work with it succumbing to this issue: ctimmerm/axios-mock-adapter#116 (comment) Tried everything there, no success. Moxios, is the one I've first chosen and used in previous commits. It's older, not updated in years and more problematic is that it's prone to "heisenbugs", i.e: randomly breaking for no obvious reason. I haven't tried jasmine-ajax, but I figured it's much more time-effective and reliable to fake the API instead (we are talking about unit tests here, so they should be isolated from the real implementation). Bonus point is that we can use the fake API to test and prototype API endpoints with sample data before implementing for real (and thus being able to try multiple designs). In the future, we should revisiting the async mocking libraries as that's the long-term proper practice.
This is really frustrating. I was convinced that it was throwing a 404 because the url was fake. Is it not possible to log that a request was made and no match was found? If there is a way to detect a no match, then there is a way to soft fail right? Add more context here? https://github.com/ctimmerm/axios-mock-adapter/blob/master/src/handle_request.js#L131 Or have the default behaviour as throw an exception stating no match was found. Would it not be better to fail early and give a contextual error? |
yeah, the same using Redux, but why is it? |
interesting thing is If I call
|
I was experiencing the same issue at my first try. I found out when use const mocker = new MockAdapter(axios);
// Declare your mock
mocker.onGet('/user').reply(200, {});
// this must be the last line! it tell any endpoint doesn't match will let it pass through
mocker.onAny().passThrough(); Hope it help! |
I haven't investigated too deeply yet, but axios-mock-adapter was working great for me on a very large project. After upgrading from webpack 4 to webpack 5 (with a few changes to babel for the polyfill changes), I suddenly started receiving 404's back in all of our unit tests. Almost everything else appears to be working, and the app still functions properly in a web browser. |
Just closing the loop on my previous comment in case if helps someone else who stumbles into this thread. My issue was that karma-webpack needed a few more changes to work properly with webpack 5. This wasn't at all apparent because the only symptom was the 404's coming from axios-mock-adapter. I conditionally added the following lines to my webpack config for unit tests only and then everything started working again: optimization: {
runtimeChunk: false,
splitChunks: false
}, Magic! |
In my case the reasoning was pure fun & had nothing to do with I use I had // ../services/http.ts
import axios from 'axios';
import axiosRetry from 'axios-retry';
const http = axios.create({
timeout: 1 * 1000 * 15,
});
axiosRetry(http, {
retries: 3,
retryDelay: axiosRetry.exponentialDelay,
});
export default http; Then, in tests I (sure) forgot about this fact & tried to use: // some.test.ts
const httpMock = new MockAdapter(http);
// ...
httpMock
.onGet('...')
.replyOnce(500); After the first I worked around that by mocking my // some.test.ts
import axios from 'axios';
jest.mock('../services/http', () => require('axios'));
const axiosMock = new MockAdapter(axios);
// ...
axiosMock
.onGet('...')
.replyOnce(500); |
import axios, { AxiosRequestConfig } from 'axios';
import MockAdapter from "axios-mock-adapter";
const mock = new MockAdapter(axios);
// Update the endpoint to match the actual application endpoint
mock.onPost("http://localhost:3110/mockApi").reply(200, {
users: [{ id: 1, name: "John Smith" }],
});
const url = "http://localhost:3110/mockApi";
(async () => {
const config: AxiosRequestConfig<any> = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
data: {
'$mock': 'TEST_DATA'
}
}
try {
const response: any = await axios(url, config);
console.log("response->", response);
} catch (error) {
console.error("Error:", error);
}
})(); Proposed Solution:
I was able to intercept axios-mock-adapter onPost request |
I don't know if it's the same issue or not but my mock requests also failed w/ 404 status and the problem for me was that the axios instance added default headers such as
To:
Hope that helps. |
pretty sure this happens with I also did try change the call itself from Finally I do find a hacky workaround, just simply do it this way, and check your call's url and other stuff in the callback, and make sure it's the call u wanna test...
|
i am using axios-mock-adapter to mock tests in react app.
got below error while running single test but it is passing in case of all tests.
/home/dev/code/client/node_modules/react-scripts/scripts/test.js:22
throw err;
^
Error: Request failed with status code 404
at createErrorResponse (/home/dev/code/client/node_modules/axios-mock-adapter/src/utils.js:122:15)
at Object.settle (/home/dev/code/client/node_modules/axios-mock-adapter/src/utils.js:102:16)
at handleRequest (/home/dev/code/client/node_modules/axios-mock-adapter/src/handle_request.js:69:11)
at /home/dev/code/client/node_modules/axios-mock-adapter/src/index.js:16:9
at MockAdapter. (/home/dev/code/client/node_modules/axios-mock-adapter/src/index.js:15:14)
at dispatchRequest (/home/dev/code/client/node_modules/axios/lib/core/dispatchRequest.js:52:10)
The text was updated successfully, but these errors were encountered: