Skip to content
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 + Axios mocking #2369

Open
1 task
p-sebastian opened this issue Nov 26, 2024 · 0 comments
Open
1 task

React Native + Axios mocking #2369

p-sebastian opened this issue Nov 26, 2024 · 0 comments
Labels

Comments

@p-sebastian
Copy link

p-sebastian commented Nov 26, 2024

Scope

Adds a new behavior

Compatibility

  • This is a breaking change

Feature description

Axios + React Native, doesn't currently work out of the box. After a few back and forth between the different similar issues opened, there is a way to make it work with version msw: 2.1.7 and "@mswjs/interceptors": "0.25.12"

If you update to latest it breaks because of a new dependency not available in react native

"resolutions": {
  "@mswjs/interceptors": "0.25.12",
  "msw": "2.1.7"
},
yarn add -D react-native-polyfill-globals react-native-url-polyfill web-streams-polyfill fast-text-encoding
// msw.polyfills.ts
import 'fast-text-encoding'
// This file was adapted from: https://github.com/facebook/react-native/issues/27741#issuecomment-2362901032
import { polyfill } from 'react-native-polyfill-globals/src/fetch'
import 'react-native-url-polyfill/auto'
// 👇 https://stackoverflow.com/a/77744609/14056591
import { ReadableStream as ReadableStreamPolyfill } from 'web-streams-polyfill/dist/ponyfill'

polyfill()

// @ts-ignore
globalThis.ReadableStream = ReadableStreamPolyfill
// msw.handlers.ts
import { http, HttpResponse } from 'msw'

export const handlers = [
	http.get(`my/url/string`, () => {
		return new HttpResponse.json({ test: 'hello' })
	}),
]

Patches

with npx patch-package

mswjs+interceptors+0.25.12.patch

diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-5RW2GLTJ.js b/node_modules/@mswjs/interceptors/lib/browser/chunk-5RW2GLTJ.js
index f9dbf7e..7117967 100644
--- a/node_modules/@mswjs/interceptors/lib/browser/chunk-5RW2GLTJ.js
+++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-5RW2GLTJ.js
@@ -58,13 +58,16 @@ var _FetchInterceptor = class extends _chunkG5ORGOKHjs.Interceptor {
       this.logger.info("awaiting for the mocked response...");
       const signal = interactiveRequest.signal;
       const requestAborted = new (0, _deferredpromise.DeferredPromise)();
-      signal.addEventListener(
-        "abort",
-        () => {
-          requestAborted.reject(signal.reason);
-        },
-        { once: true }
-      );
+      // Signal isn't always defined in react-native.
+      if (signal) {
+        signal.addEventListener(
+          "abort",
+          () => {
+            requestAborted.reject(signal.reason);
+          },
+          { once: true }
+        );
+      }
       const resolverResult = await _until.until.call(void 0, async () => {
         const listenersFinished = _chunkX3NRJIZWjs.emitAsync.call(void 0, this.emitter, "request", {
           request: interactiveRequest,
@@ -105,7 +108,9 @@ var _FetchInterceptor = class extends _chunkG5ORGOKHjs.Interceptor {
           request: interactiveRequest,
           requestId
         });
-        const response = new Response(mockedResponse.body, mockedResponse);
+        // const response = new Response(mockedResponse.body, mockedResponse);
+        // response.body is undefined in react-native.
+        const response = mockedResponse.clone();
         Object.defineProperty(response, "url", {
           writable: false,
           enumerable: true,
diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-PYOA2PFX.mjs b/node_modules/@mswjs/interceptors/lib/browser/chunk-PYOA2PFX.mjs
index ab3d22e..0553350 100644
--- a/node_modules/@mswjs/interceptors/lib/browser/chunk-PYOA2PFX.mjs
+++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-PYOA2PFX.mjs
@@ -432,7 +432,14 @@ var XMLHttpRequestController = class {
         total: totalResponseBodyLength
       });
     };
-    if (response.body) {
+    if (response._body._bodyInit) {
+      this.logger.info('mocked response has _bodyInit, faking streaming...')
+
+      const bodyInit = response._body._bodyInit
+      const encoder = new TextEncoder()
+      this.responseBuffer = encoder.encode(bodyInit)
+      finalizeResponse()
+    } else if (response.body) {
       this.logger.info("mocked response has body, streaming...");
       const reader = response.body.getReader();
       const readNextResponseBodyChunk = async () => {
@@ -523,6 +530,7 @@ var XMLHttpRequestController = class {
       return null;
     }
     const contentType = this.request.getResponseHeader("Content-Type") || "";
+    console.warn('HERE')
     if (typeof DOMParser === "undefined") {
       console.warn(
         "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."
diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-XIARBQ4Q.js b/node_modules/@mswjs/interceptors/lib/browser/chunk-XIARBQ4Q.js
index 0c3c04c..8353421 100644
--- a/node_modules/@mswjs/interceptors/lib/browser/chunk-XIARBQ4Q.js
+++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-XIARBQ4Q.js
@@ -432,7 +432,15 @@ var XMLHttpRequestController = class {
         total: totalResponseBodyLength
       });
     };
-    if (response.body) {
+
+    if (response._body._bodyInit) {
+      this.logger.info('mocked response has _bodyInit, faking streaming...')
+
+      const bodyInit = response._body._bodyInit
+      const encoder = new TextEncoder()
+      this.responseBuffer = encoder.encode(bodyInit)
+      finalizeResponse()
+    } else if (response.body) {
       this.logger.info("mocked response has body, streaming...");
       const reader = response.body.getReader();
       const readNextResponseBodyChunk = async () => {
diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-B7VH2MOR.js b/node_modules/@mswjs/interceptors/lib/node/chunk-B7VH2MOR.js
index 9711daa..e773878 100644
--- a/node_modules/@mswjs/interceptors/lib/node/chunk-B7VH2MOR.js
+++ b/node_modules/@mswjs/interceptors/lib/node/chunk-B7VH2MOR.js
@@ -434,7 +434,14 @@ var XMLHttpRequestController = class {
         total: totalResponseBodyLength
       });
     };
-    if (response.body) {
+    if (response._body._bodyInit) {
+      this.logger.info('mocked response has _bodyInit, faking streaming...')
+
+      const bodyInit = response._body._bodyInit
+      const encoder = new TextEncoder()
+      this.responseBuffer = encoder.encode(bodyInit)
+      finalizeResponse()
+    } else if (response.body) {
       this.logger.info("mocked response has body, streaming...");
       const reader = response.body.getReader();
       const readNextResponseBodyChunk = async () => {
diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-N5ZHB3BO.mjs b/node_modules/@mswjs/interceptors/lib/node/chunk-N5ZHB3BO.mjs
index 2d0df71..552d66b 100644
--- a/node_modules/@mswjs/interceptors/lib/node/chunk-N5ZHB3BO.mjs
+++ b/node_modules/@mswjs/interceptors/lib/node/chunk-N5ZHB3BO.mjs
@@ -434,7 +434,14 @@ var XMLHttpRequestController = class {
         total: totalResponseBodyLength
       });
     };
-    if (response.body) {
+    if (response._body._bodyInit) {
+      this.logger.info('mocked response has _bodyInit, faking streaming...')
+
+      const bodyInit = response._body._bodyInit
+      const encoder = new TextEncoder()
+      this.responseBuffer = encoder.encode(bodyInit)
+      finalizeResponse()
+    } else if (response.body) {
       this.logger.info("mocked response has body, streaming...");
       const reader = response.body.getReader();
       const readNextResponseBodyChunk = async () => {

References

#1926
#2344
#2026
https://stackoverflow.com/questions/56207968/stream-api-with-fetch-in-a-react-native-app/77089139#77089139

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant