-
-
Notifications
You must be signed in to change notification settings - Fork 535
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
React Native Msw And Axios Not Working Together #2026
Comments
Not sure If I have the same issue but I'm encounter issue with nest.js module "@nestjs/axios". This is some info about the console error. ● Notification controller › Notification controller in test mode › should call POST /api/notifications IN TEST MODE with type of LIVE_SESSION successfully
TypeError: Cannot read properties of null (reading 'readable')
● Notification controller › Notification controller in test mode › should call POST /api/notifications IN TEST MODE with type of LIVE_SESSION successfully
TypeError: body.getReader is not a function
at _NodeClientRequest.respondWith (../../node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/NodeClientRequest.ts:555:31)
at ../../node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/NodeClientRequest.ts:317:14
"msw": "^2.2.0", BTW, it works fine if I return error return new HttpResponse(null, {status: 400}); |
I have a same issue too... |
I'm experiencing a similar issue, where it is not recognizing the axios post method, returning this error, Version of MSW: |
I also ran into axios-related issues with msw. My workaround is to mock axios to use fetch for the requests within my vitest suite. This should also be applicable to Jest (using Solution that works for me in a test setup file: beforeAll(() => {
// axios needs to be mocked to use fetch in order to work with msw
vi.mock("axios", () => {
const isAxiosError = (error: any) => error.isAxiosError === true;
const handleAxiosResponse = async (response: Response) => {
if (!response.ok) {
// eslint-disable-next-line @typescript-eslint/no-throw-literal
throw {
isAxiosError: true,
message: response.statusText,
response: {
status: response.status,
statusText: response.statusText,
data: null,
headers: {},
config: {},
},
};
}
const data = await response.json();
return { data };
};
const handleError = (error: any) => {
throw isAxiosError(error)
? error
: {
isAxiosError: true,
message: error.message,
};
};
const cleanUpParams = (params?: Record<string, string | undefined>) => {
return Object.fromEntries(
Object.entries(params ?? {}).filter(
(entry): entry is [string, string] => entry[1] !== undefined,
),
);
};
const getMethodHandler =
(method: string) => async (url: string, config?: any) => {
const queryString = new URLSearchParams(
cleanUpParams(config?.params),
).toString();
const modifiedUrl = `${url}?${queryString}`;
return await fetch(modifiedUrl, { ...config, method })
.then(handleAxiosResponse)
.catch(handleError);
};
const getMethodHandlerWithBody =
(method: string) => async (url: string, data?: any, config?: any) => {
const queryString = new URLSearchParams(
cleanUpParams(config?.params),
).toString();
const modifiedUrl = `${url}?${queryString}`;
const fetchConfig = {
...config,
method,
body: data ? JSON.stringify(data) : undefined,
};
return await fetch(modifiedUrl, fetchConfig)
.then(handleAxiosResponse)
.catch(handleError);
};
return {
default: {
delete: getMethodHandler("DELETE"),
get: getMethodHandler("GET"),
head: getMethodHandler("HEAD"),
patch: getMethodHandlerWithBody("PATCH"),
post: getMethodHandlerWithBody("POST"),
put: getMethodHandlerWithBody("PUT"),
},
isAxiosError,
};
});
}); |
I was stumped by this problem for a while. I found that fetch was working fine, but axios just kept failing. The MSW server handler was not intercepting the network request and my axios.get() call failed with an 'ENOTFOUND' error as it couldn't resolve the sysaddrinfo() call on my dummy URL. Eventually though, I did find a very simple solution that worked for me... I switched the import of setupServer from 'msw/native' to 'msw/node' o_0
|
Just want to also chime in here and say I'm seeing the same issue where the body is undefined/null when using MSW, Axios, and React Native:
Fetch works fine! I've followed the basic set up steps in repo. I see similar comments: #1775 (comment) and here: #1926 (comment) (same user) It sounds like it's somehow related to the XMLHttpRequest interceptor/stack...I do notice that it seems to be hitting the /browser codepath, and not the /node/native codepath (if that matters). |
Same problem here. Using MSW with Axios in React Native doesn't work. The request response is not finalized and does not return the JSON as it should. |
Hey @kettanaito I've set up a basic reproducible example here (as simple as I could): https://github.com/zibs/mvce-msw-rn if you have the chance to take a look. The warning that is thrown in the video is " Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly.", but I don't think is totally relevant (but maybe?)... I'm happy to continue digging in, but you might be able to diagnose it much faster! When digging I noticed that here https://github.com/mswjs/interceptors/blob/133754688adeb47cb972ab358db5e77f30084e03/src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts#L335 there is never a Let me know if you want a separate issue created or anything. |
Yeah, React Native doesn't natively support a React Native also doesn't natively support |
I've been looking at this over here: #2085 and have narrowed something similar down to a repro. When you run msw/axios in an environment that uses the node >= 18 APIs for Request/Response, everything works. But when running in an environment that gets those APIs from elsewhere - specifically whatwg-fetch, which is common in react projects in the testing environment, not sure about react-native but I did notice the dependency in @zibs repo - then it's borked. |
This is not an issue with MSW, it's an issue with whatwg-fetch - I think this one - which might make it an issue to be raised over there (although the one I've referenced is closed), or perhaps an issue could be raised in react-native to use a different polyfill. EDIT: Also same issue in RN repo. Hey, at least that one's open! |
First of all, thank you all very much for your answers, I could not follow the issues for a while. I used an alternative library as a solution, thank you. |
Handler: http.get('*', ({ request }) => {
return HttpResponse.json({
data: { bebe: 1 },
});
})
|
I've found workaround. We can use diff --git a/lib/browser/chunk-65PS3XCB.js b/lib/browser/chunk-65PS3XCB.js
index e4f824e7d40d3d2a48c86b2420cbfd8e7c2c53ed..07228344b25fb6b44bb396f4b9eb93332d11cac2 100644
--- a/lib/browser/chunk-65PS3XCB.js
+++ b/lib/browser/chunk-65PS3XCB.js
@@ -455,6 +455,13 @@ var XMLHttpRequestController = class {
readNextResponseBodyChunk();
};
readNextResponseBodyChunk();
+ } else if (response._bodyInit) {
+ this.logger.info('mocked response has _bodyInit, faking streaming...')
+
+ const bodyInit = response._bodyInit
+ const encoder = new TextEncoder()
+ this.responseBuffer = encoder.encode(bodyInit)
+ finalizeResponse()
} else {
finalizeResponse();
} Here is fixed logs:
|
@kettanaito Can this workaround to be useful inside interceptors package? |
Any fix planned ? |
@hardouinyann you can use my patch for now |
For anybody who comes across this, this patch needs to be applied on the |
Yep that's true |
It's working! I hope it will merge asap! thank you! @XantreDev |
I would like to provide a PR if @kettanaito consider it usefull |
@kettanaito is this fix something you'd consider merging? (asking because this issue is closed at the moment) I'd rather only apply a patch as a stopgap for a proper fix, otherwise MSW just isn't an option for us for now :( |
@kettanaito, any update on this? |
@kettanaito Hello! |
When I make requests to msw handlers, axios returns empty strings as data for some reason, but when I make requests with fetch, the data comes correctly. when I check if the handlers are triggered, the handlers are triggered. When I make a request to another api I get data with axios. can you help me to solve the problem?
index.js
server.js
My Fetch Method:
handlers.js:
The Console Log Here Works Both In Fetch And In Axios
Node Version : v18.13.0
The text was updated successfully, but these errors were encountered: