You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Following React Native docs does not work and Property 'TransformStream' doesn't exist on React Native (runtime) #2367
Bug 1: Seems that React Native does not support the dynamic import syntax and fails to register the component in time.
Bug 2: Property 'TransformStream' doesn't exist on React Native at runtime running the synchronous code. This would also occur if the async version (bug 1) worked
Expected behavior
Bug 1: I expect the docs to explain how to get this working with additional metro config or a complete example with Metro and RN CLI. I expect the docs to accurately describe how to get msw to work in React Native.
Bug 2: I expect this to work on React Native like the docs suggest.
Async error (main)
Sync error (bug/sync)
Reacted by vonkanehoffen, Sacha Hergibo, TheProcessorCodes, Abhimanyu Pathania, Frederic R., Ali, Gabriel França, holubiev, loudy and andrew ananta gondo 🎏
changed the title [-]Following React Native does not work and Property 'TransformStream' doesn't exist on React Native (runtime)[/-][+]Following React Native docs does not work and Property 'TransformStream' doesn't exist on React Native (runtime)[/+]on Nov 22, 2024
We should introduce a separate export condition for react-native to exclude the Brotli decompressor from that environment. The decompression relies on the standard TransformStream web API that doesn't exist in React Native, sadly.
@kettanaito I'm sure I'm doing something wrong but I tried to comment out this line or well changed it do const decompressedStream = null and comment any other decompression imports in my node_modules and some how I still see ReferenceError: Property 'TransformStream' doesn't exist when I start my server
Sadly, what ended up working for me is downgrading msw to 2.4.11
I took it from this issue: #2344
I think that react native compatibility should be removed or there must be some work to be done with the documentation.
I followed the documentation and also installed jest-fixed-jsdom as @kettanaito suggested in the other issue, and I'm still getting problems, I even started to add this libraries to the polyfill but keep getting different compilation errors.
Edit: Spoke too soon it did get me past the TransformStream issue but now I'm seeing something about MessageEvent.
@kettanaito I've also experienced this same error after adding web-streams-polyfill. Digging into this further, the cause is dependencies on core WebSocket handling code used by SetupServerCommonApi, which itself depends on MessageEvent:
I wonder if WebSocket interception could be implemented using MessageEvent?
Edit: I've managed to make some progress by patching out the WebSocket interceptor. This isn't ideal but at least allowed me to continue discovery. Once I got around the WebSocket interceptor, I encountered an issue with the Document global being accessed from the XMLHttpRequest browser interceptor, which isn't available in React Native. I had to apply another patch to make sure the global was checked first before access. This has gotten me past the runtime errors, but I"m now running into problems with matched requests remaining unresolved.
diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-ZIT2QX7D.js b/node_modules/@mswjs/interceptors/lib/browser/chunk-ZIT2QX7D.js
index 8a8b74e..daebb90 100644
--- a/node_modules/@mswjs/interceptors/lib/browser/chunk-ZIT2QX7D.js+++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-ZIT2QX7D.js@@ -502,6 +502,7 @@ var XMLHttpRequestController = class {
total: totalResponseBodyLength
});
};
+
if (response.body) {
this.logger.info("mocked response has body, streaming...");
const reader = response.body.getReader();
@@ -662,7 +663,7 @@ var XMLHttpRequestController = class {
*/
toFetchApiRequest(body) {
this.logger.info("converting request to a Fetch API Request...");
- const resolvedBody = body instanceof Document ? body.documentElement.innerText : body;+ const resolvedBody = globalThis.Document && body instanceof Document ? body.documentElement.innerText : body;
const fetchRequest = new Request(this.url.href, {
method: this.method,
headers: this.requestHeaders,
Edit 2: Following up on my previous edit, the reason why mocked requests weren't resolving is due to a code path in XMLHttpRequestController.trigger that accesses XMLHttpRequestUpload. React Native's implementation of XMLHttpRequest uses XMLHttpRequestEventTarget as the underlying implementation for XMLHttpRequestUpload. The implementation is also not available on globalThis, leading to a runtime error when attempting to use mocked responses. @kettanaito FYI This is the exact line of code causing the issue: https://github.com/mswjs/interceptors/blob/a9fd7cf55c4413d9e3fa50f5ae7559b4c81051f7/src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts#L635.
Edit 3: Got the latest msw working on React Native 🎉 ! The last piece of the puzzle was documented in this issue. Applying the fetch polyfill and patch to use response._body._bodyInit was the last change needed.
Reacted by Ben Winters, TheProcessorCodes, Alec Winograd, Eric Kreutzer and AbdallahAbuHashem
Thanks a lot @tranhl for the steps here! I got things to run based on your edits. For the XMLHttpRequestUpload issue the only thing that worked for me is to just do: const events = this.uploadEvents;, which doesn't seem correct. I dug deeper, and it seems that on this.events the load call breaks as it has a null value for the response headers, which is not expected downstream. I'm curious if you have a better solution, thanks in advance 🙏
@freitagdavid The issue might be related to the imported event-target-shim polyfill. I've ended up writing the necessary minimal polyfills for MessageEvent, Event, EventTarget myself, without any imports. That’s doing the trick for my needs so far.
The only polypill you actually need is web-streams-polyfill. As @nikita-leonov pointed out earlier, there's no need for react-native-url-polyfill or fast-text-encoding
somehow this polyfill config works for me , i'm using version 2.12.14
msw.polyfills.js
import"fast-text-encoding";import"react-native-url-polyfill/auto";import"web-streams-polyfill/dist/polyfill";import{ReadableStream,WritableStream,TransformStream}from"web-streams-polyfill";if(typeofglobal.ReadableStream==="undefined"){global.ReadableStream=ReadableStream;}if(typeofglobal.WritableStream==="undefined"){global.WritableStream=WritableStream;}if(typeofglobal.TransformStream==="undefined"){global.TransformStream=TransformStream;}if(typeofglobal.Event==="undefined"){global.Event=functionEvent(type,eventInitDict={}){this.type=type;this.bubbles=eventInitDict.bubbles||false;this.cancelable=eventInitDict.cancelable||false;this.target=null;this.currentTarget=null;this.eventPhase=0;this.defaultPrevented=false;this.isTrusted=false;this.preventDefault=function(){this.defaultPrevented=true;};};}if(typeofglobal.EventTarget==="undefined"){global.EventTarget=functionEventTarget(){this.listeners={};};global.EventTarget.prototype.addEventListener=function(type,callback){if(!this.listeners[type]){this.listeners[type]=[];}this.listeners[type].push(callback);};global.EventTarget.prototype.removeEventListener=function(type,callback){if(!this.listeners[type])return;this.listeners[type]=this.listeners[type].filter((cb)=>cb!==callback);};global.EventTarget.prototype.dispatchEvent=function(event){if(!this.listeners[event.type])returntrue;this.listeners[event.type].forEach((cb)=>cb.call(this,event));return!event.defaultPrevented;};}if(typeofglobal.MessageEvent==="undefined"){global.MessageEvent=functionMessageEvent(type,eventInitDict={}){this.type=type;this.data=eventInitDict.data||null;this.origin=eventInitDict.origin||"";this.lastEventId=eventInitDict.lastEventId||"";this.source=eventInitDict.source||null;this.ports=eventInitDict.ports||[];};}if(typeofBroadcastChannel==="undefined"){global.BroadcastChannel=classBroadcastChannelextendsglobal.EventTarget{constructor(channelName){super();this.channelName=channelName;this._subscribers=[];}postMessage(message){constevent=newglobal.MessageEvent("message",{data: message,});setTimeout(()=>{this.dispatchEvent(event);},0);}close(){this._subscribers=[];}};}// XMLHttpRequestUpload is used by MSW's XHR interceptor at module evaluation.// Hermes provides XMLHttpRequest but not XMLHttpRequestUpload.if(typeofglobal.XMLHttpRequestUpload==='undefined'){global.XMLHttpRequestUpload=functionXMLHttpRequestUpload(){};global.XMLHttpRequestUpload.prototype=Object.create(global.EventTarget ? global.EventTarget.prototype : Object.prototype);}// React Native's XHR returns null from getAllResponseHeaders() when there are// no headers yet. MSW's XHR interceptor calls .split() on that value and crashes.if(typeofglobal.XMLHttpRequest!=='undefined'){const_getAllResponseHeaders=global.XMLHttpRequest.prototype.getAllResponseHeaders;global.XMLHttpRequest.prototype.getAllResponseHeaders=function(){return_getAllResponseHeaders.call(this)??'';};}
I got msw/native working in a React Native (Expo, Hermes) app for E2E testing with Maestro. It required several undocumented polyfills that aren't mentioned in the React Native integration docs.
Issue 1: globalThis.fetch is non-writable in Hermes
This is the most critical one. MSW's FetchInterceptor does globalThis.fetch = interceptedFetch, but Hermes exposes fetch as a non-configurable native binding. The assignment silently fails — no error thrown, MSW reports it's listening, but no requests are intercepted.
Fix: delete and re-define the property before importing MSW:
MSW's core module (ws.js, sse.js) references BroadcastChannel, EventTarget, Event, and MessageEvent at module evaluation time (not inside functions). Hermes doesn't provide these. They must be polyfilled before any MSW import:
Import order matters: these polyfills must run before setupServer from msw/native or any handler file that imports http/HttpResponse from msw.
Context: I'm using MSW 2.12.4 with Expo SDK 55, Hermes, React Native 0.83. I use msw/native for Maestro E2E tests with mocked API responses. Happy to contribute a PR to update the React Native docs if helpful.
Reacted by Artem Zakharchenko and Anderson Rodriguez Casado
Opened mswjs/interceptors#777 for the TransformStream import-time crash. It adds a react-native export condition that points to a lib/native/ build where internal:decompression is aliased to a no-op returning null, matching the direction @kettanaito suggested above.
Scope is just the fetch interceptor, since that's what msw/native consumes today. The other Hermes gaps mentioned in this thread (MessageEvent, Document / XMLHttpRequestUpload in the XHR interceptor, non-configurable globalThis.fetch) aren't covered and would need separate PRs.
MSW relies heavily on web streams so they must be polyfilled on the testing environment level. web-streams-polyfill seems to be a good choice for that. The library cannot realistically support environments where web streams don't exist.
In any case, this looks extremely aggressive and Hermes shouldn't be doing this. At least, set a non-configurable property with writable: true to allow reassignments. I will add support for patching non-configurable writable globals in mswjs/interceptors#780, but the rest has to be handled on Hermes' side.
The missing APIs on import time is also the import leak problem we are addressing as a part of #2687 in #2692. Unless you actually import from msw/sse/msw/ws/etc, you won't have to deal with the global APIs used by the respective modules.
I need to get my hands on running tests in Hermes. I've no idea what that is. I'm wondering if there's no Node.js at all there, otherwise you can grab the implementation for Event/EventTarget/BroadcastChannel from Node.js directly.
Hey @kettanaito - if you want a sample Jest setup for React Native, you could take a look at https://github.com/infinitered/ignite (or run npx ignite-cli@latest new PizzaApp and run the test suite.
But beware - running JS tests in Jest against React Native won't really test out the Hermes capability.
Hermes is the JS engine that React Native uses by default. It runs in the Android and iOS operating systems. But when you run Jest tests against React Native codebases, Jest runs in Node, so you'll end up in a spot where you're not really exercising the Hermes engine.
I haven't ever found a good way to run my jest specs in Hermes, but I did see this in my feeds recently (I do not know it so I can't say if it works/is safe/etc.): https://github.com/marcuzgabriel/hermes-test
We recently used MSW on a larger project at Infinite Red. we liked it a lot, but ran into some issues. I'm working on some follow up documentation internally. If you ever want to chat I'd be happy to give you some RN pointers (and I'd love to learn more about MSW as well).
Activity
[-]Following React Native does not work and Property 'TransformStream' doesn't exist on React Native (runtime)[/-][+]Following React Native docs does not work and Property 'TransformStream' doesn't exist on React Native (runtime)[/+]kettanaito commentedon Nov 24, 2024
Hi, @lgibso34. Thanks for reporting this!
We should introduce a separate export condition for
react-nativeto exclude the Brotli decompressor from that environment. The decompression relies on the standardTransformStreamweb API that doesn't exist in React Native, sadly.This is a pull request for https://github.com/mswjs/interceptors.
kettanaito commentedon Nov 24, 2024
Do you know if there's a list of all global APIs in React Native? I doubt there's
DecompressionStreamthere either.TheProcessorCodes commentedon Nov 24, 2024
I do not, sorry. Thanks for responding though and taking a look.
TheProcessorCodes commentedon Nov 24, 2024
@kettanaito I'm sure I'm doing something wrong but I tried to comment out this line or well changed it do
const decompressedStream = nulland comment any other decompression imports in mynode_modulesand some how I still seeReferenceError: Property 'TransformStream' doesn't existwhen I start my serverfreitagdavid commentedon Dec 5, 2024
Found a workaround it looks like this polyfill can get things working for the time being if you add it to your msw.polyfill.js file.
https://github.com/MattiasBuelens/web-streams-polyfill
Edit: Spoke too soon it did get me past the TransformStream issue but now I'm seeing something about MessageEvent.
ibrust commentedon Jan 2, 2025
Is there a version of MSW where this is not an issue?
mcanessa commentedon Jan 6, 2025
Sadly, what ended up working for me is downgrading msw to 2.4.11
I took it from this issue: #2344
I think that react native compatibility should be removed or there must be some work to be done with the documentation.
I followed the documentation and also installed jest-fixed-jsdom as @kettanaito suggested in the other issue, and I'm still getting problems, I even started to add this libraries to the polyfill but keep getting different compilation errors.
erickreutz commentedon Jan 23, 2025
Any movement on this? Seems like a pretty critical issue - can't use with React Native at all..
tranhl commentedon Jan 29, 2025
@kettanaito I've also experienced this same error after adding
web-streams-polyfill. Digging into this further, the cause is dependencies on core WebSocket handling code used bySetupServerCommonApi, which itself depends onMessageEvent:msw/src/node/SetupServerCommonApi.ts
Lines 21 to 22 in e3234fd
I wonder if WebSocket interception could be implemented using
MessageEvent?Edit: I've managed to make some progress by patching out the WebSocket interceptor. This isn't ideal but at least allowed me to continue discovery. Once I got around the WebSocket interceptor, I encountered an issue with the
Documentglobal being accessed from theXMLHttpRequestbrowser interceptor, which isn't available in React Native. I had to apply another patch to make sure the global was checked first before access. This has gotten me past the runtime errors, but I"m now running into problems with matched requests remaining unresolved.Here are the polyfills and patches used:
msw+2.7.0.patch:@mswjs+interceptors+0.37.5.patch:Edit 2: Following up on my previous edit, the reason why mocked requests weren't resolving is due to a code path in
XMLHttpRequestController.triggerthat accessesXMLHttpRequestUpload. React Native's implementation ofXMLHttpRequestusesXMLHttpRequestEventTargetas the underlying implementation forXMLHttpRequestUpload. The implementation is also not available onglobalThis, leading to a runtime error when attempting to use mocked responses. @kettanaito FYI This is the exact line of code causing the issue: https://github.com/mswjs/interceptors/blob/a9fd7cf55c4413d9e3fa50f5ae7559b4c81051f7/src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts#L635.Edit 3: Got the latest
mswworking on React Native 🎉 ! The last piece of the puzzle was documented in this issue. Applying thefetchpolyfill and patch to useresponse._body._bodyInitwas the last change needed.abhimanyuPathania commentedon Feb 3, 2025
Any update on this? Still cannot use this on React Native.
Update: I ended up using Mirage JS. Was good enough for me and worked out of box.
AbdallahAbuHashem commentedon Feb 16, 2025
Thanks a lot @tranhl for the steps here! I got things to run based on your edits. For the
XMLHttpRequestUploadissue the only thing that worked for me is to just do:const events = this.uploadEvents;, which doesn't seem correct. I dug deeper, and it seems that onthis.eventstheloadcall breaks as it has a null value for the response headers, which is not expected downstream. I'm curious if you have a better solution, thanks in advance 🙏7 remaining items
faciledictu commentedon Jul 10, 2025
@freitagdavid The issue might be related to the imported
event-target-shimpolyfill. I've ended up writing the necessary minimal polyfills forMessageEvent,Event,EventTargetmyself, without any imports. That’s doing the trick for my needs so far.The only polypill you actually need is
web-streams-polyfill. As @nikita-leonov pointed out earlier, there's no need forreact-native-url-polyfillorfast-text-encodingTheProcessorCodes commentedon Jul 17, 2025
@kettanaito
Does this solve all our issues here?
"Announcing Node-API Support for React Native"
https://www.callstack.com/blog/announcing-node-api-support-for-react-native
evrimfeyyaz commentedon Sep 2, 2025
This is what ended up working for me (based on answers from @faciledictu and @nikita-leonov):
hariDasu commentedon Feb 4, 2026
I had to write a customServer instead of using MSW/native and polyfill BroadcastChannel, Event, MessageEvent, and EventChannel.
In environments I tested in
Wondering if using expo/fetch makes this simpler?
aka less polyfills, probably still need to monkey patch
global.fetchfor msw interceptor to workanztrax commentedon Mar 28, 2026
somehow this polyfill config works for me , i'm using version 2.12.14
msw.polyfills.jsdebitan commentedon Apr 24, 2026
I got
msw/nativeworking in a React Native (Expo, Hermes) app for E2E testing with Maestro. It required several undocumented polyfills that aren't mentioned in the React Native integration docs.Issue 1:
globalThis.fetchis non-writable in HermesThis is the most critical one. MSW's
FetchInterceptordoesglobalThis.fetch = interceptedFetch, but Hermes exposesfetchas a non-configurable native binding. The assignment silently fails — no error thrown, MSW reports it's listening, but no requests are intercepted.Fix: delete and re-define the property before importing MSW:
Issue 2: Missing Web APIs at import time
MSW's core module (
ws.js,sse.js) referencesBroadcastChannel,EventTarget,Event, andMessageEventat module evaluation time (not inside functions). Hermes doesn't provide these. They must be polyfilled before any MSW import:Import order matters: these polyfills must run before
setupServerfrommsw/nativeor any handler file that importshttp/HttpResponsefrommsw.Context: I'm using MSW 2.12.4 with Expo SDK 55, Hermes, React Native 0.83. I use
msw/nativefor Maestro E2E tests with mocked API responses. Happy to contribute a PR to update the React Native docs if helpful.fix(fetch): add react-native export condition to skip decompression
fix(fetch): add react-native export condition to skip decompression
vladlenskiy commentedon Apr 25, 2026
Opened mswjs/interceptors#777 for the
TransformStreamimport-time crash. It adds areact-nativeexport condition that points to alib/native/build whereinternal:decompressionis aliased to a no-op returningnull, matching the direction @kettanaito suggested above.Scope is just the fetch interceptor, since that's what
msw/nativeconsumes today. The other Hermes gaps mentioned in this thread (MessageEvent,Document/XMLHttpRequestUploadin the XHR interceptor, non-configurableglobalThis.fetch) aren't covered and would need separate PRs.kettanaito commentedon May 1, 2026
Thank you everyone for looking into this.
Web streams
MSW relies heavily on web streams so they must be polyfilled on the testing environment level.
web-streams-polyfillseems to be a good choice for that. The library cannot realistically support environments where web streams don't exist.Non-configurable
global.fetch@debitan, this is a good find. This is something we need to take into account in our patches registry before applying the patch for that global (or any other non-configurable global): https://github.com/mswjs/interceptors/blob/24858e7b89a2d0625e89a806a4b2c2cda2ead151/src/utils/patchesRegistry.ts#L3
Wait, how come you can delete the property though? Deleting is forbidden for non-configurable properties:
Can you please paste the property descriptor for global fetch in Hermes?
In any case, this looks extremely aggressive and Hermes shouldn't be doing this. At least, set a non-configurable property with
writable: trueto allow reassignments. I will add support for patching non-configurable writable globals in mswjs/interceptors#780, but the rest has to be handled on Hermes' side.kettanaito commentedon May 1, 2026
The missing APIs on import time is also the import leak problem we are addressing as a part of #2687 in #2692. Unless you actually import from
msw/sse/msw/ws/etc, you won't have to deal with the global APIs used by the respective modules.I need to get my hands on running tests in Hermes. I've no idea what that is. I'm wondering if there's no Node.js at all there, otherwise you can grab the implementation for
Event/EventTarget/BroadcastChannelfrom Node.js directly.kettanaito commentedon May 1, 2026
How does anybody even run tests with ESM? I'm 30m into making Jest understand ESM. No luck. A reproduction repository would be hugely appreciated.
coolsoftwaretyler commentedon Jul 6, 2026
Hey @kettanaito - if you want a sample Jest setup for React Native, you could take a look at https://github.com/infinitered/ignite (or run
npx ignite-cli@latest new PizzaAppand run the test suite.But beware - running JS tests in Jest against React Native won't really test out the Hermes capability.
Hermes is the JS engine that React Native uses by default. It runs in the Android and iOS operating systems. But when you run Jest tests against React Native codebases, Jest runs in Node, so you'll end up in a spot where you're not really exercising the Hermes engine.
I haven't ever found a good way to run my jest specs in Hermes, but I did see this in my feeds recently (I do not know it so I can't say if it works/is safe/etc.): https://github.com/marcuzgabriel/hermes-test
We recently used MSW on a larger project at Infinite Red. we liked it a lot, but ran into some issues. I'm working on some follow up documentation internally. If you ever want to chat I'd be happy to give you some RN pointers (and I'd love to learn more about MSW as well).
kettanaito commentedon Sep 28, 2026
Released: v3.0.0 🎉
This has been released in v3.0.0.
Get these changes by running the following command:
Predictable release automation by Release.