Skip to content

Following React Native docs does not work and Property 'TransformStream' doesn't exist on React Native (runtime) #2367

Closed

Description

@TheProcessorCodes

Prerequisites

Environment check

  • I'm using the latest msw version
  • I'm using Node.js version 18 or higher

Node.js version

v18.15.0

Reproduction repository

https://github.com/lgibso34/react-native-msw

Reproduction steps

Similar to #2344 but not Jest related.

  1. checkout main branch
  2. npm start
  3. launch on device

TransformStream error

1. git checkout bug/sync
2. npm start
3. launch on device

Current behavior

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)
not_registered

Sync error (bug/sync)
TransformStream no exist

Activity

  1. added
    bug
    needs:triage
    scope:node
    on Nov 22, 2024
  2. 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
  3. kettanaito commented on Nov 24, 2024

    @kettanaito
    Member

    Hi, @lgibso34. Thanks for reporting this!

    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.

    This is a pull request for https://github.com/mswjs/interceptors.

  4. kettanaito commented on Nov 24, 2024

    @kettanaito
    Member

    Do you know if there's a list of all global APIs in React Native? I doubt there's DecompressionStream there either.

  5. TheProcessorCodes commented on Nov 24, 2024

    @TheProcessorCodes
    Author

    exclude the Brotli deco

    I do not, sorry. Thanks for responding though and taking a look.

  6. TheProcessorCodes commented on Nov 24, 2024

    @TheProcessorCodes
    Author

    @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

  7. freitagdavid commented on Dec 5, 2024

    @freitagdavid

    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.

  8. ibrust commented on Jan 2, 2025

    @ibrust

    Is there a version of MSW where this is not an issue?

  9. mcanessa commented on Jan 6, 2025

    @mcanessa

    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.

  10. erickreutz commented on Jan 23, 2025

    @erickreutz

    Any movement on this? Seems like a pretty critical issue - can't use with React Native at all..

  11. tranhl commented on Jan 29, 2025

    @tranhl

    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.

    MattiasBuelens/web-streams-polyfill

    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:

    import { handleWebSocketEvent } from '~/core/ws/handleWebSocketEvent'
    import { webSocketInterceptor } from '~/core/ws/webSocketInterceptor'

    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.

    Here are the polyfills and patches used:

    import "fast-text-encoding";
    import "react-native-url-polyfill/auto";
    import "web-streams-polyfill/dist/polyfill";

    msw+2.7.0.patch:

    diff --git a/node_modules/msw/lib/core/index.js b/node_modules/msw/lib/core/index.js
    index f07b0da..9852133 100644
    --- a/node_modules/msw/lib/core/index.js
    +++ b/node_modules/msw/lib/core/index.js
    @@ -32,7 +32,6 @@ __export(core_exports, {
       http: () => import_http.http,
       matchRequestUrl: () => import_matchRequestUrl.matchRequestUrl,
       passthrough: () => import_passthrough.passthrough,
    -  ws: () => import_ws.ws
     });
     module.exports = __toCommonJS(core_exports);
     var import_checkGlobals = require("./utils/internal/checkGlobals.js");
    @@ -42,7 +41,6 @@ var import_http = require("./http.js");
     var import_HttpHandler = require("./handlers/HttpHandler.js");
     var import_graphql = requirie("./graphql.js");
     var import_GraphQLHandler = require("./handlers/GraphQLHandler.js");
    -var import_ws = require("./ws.js");
     var import_WebSocketHandler = require("./handlers/WebSocketHandler.js");
     var import_matchRequestUrl = require("./utils/matching/matchRequestUrl.js");
     __reExport(core_exports, require("./utils/handleRequest.js"), module.exports);
    diff --git a/node_modules/msw/lib/native/index.js b/node_modules/msw/lib/native/index.js
    index d2e478d..3a80812 100644
    --- a/node_modules/msw/lib/native/index.js
    +++ b/node_modules/msw/lib/native/index.js
    @@ -33,8 +33,6 @@ var import_SetupApi = require("../core/SetupApi.js");
     var import_handleRequest = require("../core/utils/handleRequest.js");
     var import_mergeRight = require("../core/utils/internal/mergeRight.js");
     var import_devUtils = require("../core/utils/internal/devUtils.js");
    -var import_handleWebSocketEvent = require("../core/ws/handleWebSocketEvent.js");
    -var import_webSocketInterceptor = require("../core/ws/webSocketInterceptor.js");
     var import_isHandlerKind = require("../core/utils/internal/isHandlerKind.js");
     var DEFAULT_LISTEN_OPTIONS = {
       onUnhandledRequest: "warn"
    @@ -104,18 +102,6 @@ var SetupServerCommonApi = class extends import_SetupApi.SetupApi {
             );
           }
         );
    -    (0, import_handleWebSocketEvent.handleWebSocketEvent)({
    -      getUnhandledRequestStrategy: () => {
    -        return this.resolvedOptions.onUnhandledRequest;
    -      },
    -      getHandlers: () => {
    -        return this.handlersController.currentHandlers();
    -      },
    -      onMockedConnection: () => {
    -      },
    -      onPassthroughConnection: () => {
    -      }
    -    });
       }
       listen(options = {}) {
         this.resolvedOptions = (0, import_mergeRight.mergeRight)(
    @@ -125,8 +111,6 @@ var SetupServerCommonApi = class extends import_SetupApi.SetupApi {
         this.interceptor.apply();
         this.init();
         this.subscriptions.push(() => this.interceptor.dispose());
    -    import_webSocketInterceptor.webSocketInterceptor.apply();
    -    this.subscriptions.push(() => import_webSocketInterceptor.webSocketInterceptor.dispose());
         (0, import_outvariant.invariant)(
           [import_interceptors.InterceptorReadyState.APPLYING, import_interceptors.InterceptorReadyState.APPLIED].includes(
             this.interceptor.readyState
    diff --git a/node_modules/msw/lib/native/index.mjs b/node_modules/msw/lib/native/index.mjs
    index 5769843..51eadae 100644
    --- a/node_modules/msw/lib/native/index.mjs
    +++ b/node_modules/msw/lib/native/index.mjs
    @@ -12,8 +12,6 @@ import { SetupApi } from '../core/SetupApi.mjs';
     import { handleRequest } from '../core/utils/handleRequest.mjs';
     import { mergeRight } from '../core/utils/internal/mergeRight.mjs';
     import { InternalError, devUtils } from '../core/utils/internal/devUtils.mjs';
    -import { handleWebSocketEvent } from '../core/ws/handleWebSocketEvent.mjs';
    -import { webSocketInterceptor } from '../core/ws/webSocketInterceptor.mjs';
     import { isHandlerKind } from '../core/utils/internal/isHandlerKind.mjs';
     var DEFAULT_LISTEN_OPTIONS = {
       onUnhandledRequest: "warn"
    @@ -83,18 +81,6 @@ var SetupServerCommonApi = class extends SetupApi {
             );
           }
         );
    -    handleWebSocketEvent({
    -      getUnhandledRequestStrategy: () => {
    -        return this.resolvedOptions.onUnhandledRequest;
    -      },
    -      getHandlers: () => {
    -        return this.handlersController.currentHandlers();
    -      },
    -      onMockedConnection: () => {
    -      },
    -      onPassthroughConnection: () => {
    -      }
    -    });
       }
       listen(options = {}) {
         this.resolvedOptions = mergeRight(
    @@ -104,8 +90,6 @@ var SetupServerCommonApi = class extends SetupApi {
         this.interceptor.apply();
         this.init();
         this.subscriptions.push(() => this.interceptor.dispose());
    -    webSocketInterceptor.apply();
    -    this.subscriptions.push(() => webSocketInterceptor.dispose());
         invariant(
           [InterceptorReadyState.APPLYING, InterceptorReadyState.APPLIED].includes(
             this.interceptor.readyState

    @mswjs+interceptors+0.37.5.patch:

    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.

  12. abhimanyuPathania commented on Feb 3, 2025

    @abhimanyuPathania

    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.

  13. AbdallahAbuHashem commented on Feb 16, 2025

    @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 🙏

  14. 7 remaining items

  15. faciledictu commented on Jul 10, 2025

    @faciledictu

    @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.

    // msw.polyfill.js
    
    import { TransformStream } from 'web-streams-polyfill';
    
    if (typeof global.TransformStream === 'undefined') {
      global.TransformStream = TransformStream;
    }
    
    if (typeof global.MessageEvent === 'undefined') {
      global.MessageEvent = function MessageEvent(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 (typeof global.Event === 'undefined') {
      global.Event = function Event(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 (typeof global.EventTarget === 'undefined') {
      global.EventTarget = function EventTarget() {
        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]) return true;
        this.listeners[event.type].forEach((cb) => cb.call(this, event));
        return !event.defaultPrevented;
      };
    }

    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

  16. TheProcessorCodes commented on Jul 17, 2025

    @TheProcessorCodes
    Author

    @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

  17. evrimfeyyaz commented on Sep 2, 2025

    @evrimfeyyaz

    This is what ended up working for me (based on answers from @faciledictu and @nikita-leonov):

    import { TransformStream } from "web-streams-polyfill";
    
    if (typeof global.TransformStream === "undefined") {
      global.TransformStream = TransformStream;
    }
    
    if (typeof global.Event === "undefined") {
      global.Event = function Event(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 (typeof global.EventTarget === "undefined") {
      global.EventTarget = function EventTarget() {
        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]) return true;
        this.listeners[event.type].forEach((cb) => cb.call(this, event));
        return !event.defaultPrevented;
      };
    }
    
    if (typeof global.MessageEvent === "undefined") {
      global.MessageEvent = function MessageEvent(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 (typeof BroadcastChannel === "undefined") {
      global.BroadcastChannel = class BroadcastChannel extends global.EventTarget {
        constructor(channelName) {
          super();
          this.channelName = channelName;
          this._subscribers = [];
        }
    
        postMessage(message) {
          const event = new global.MessageEvent("message", {
            data: message,
          });
    
          setTimeout(() => {
            this.dispatchEvent(event);
          }, 0);
        }
    
        close() {
          this._subscribers = [];
        }
      };
    }
  18. hariDasu commented on Feb 4, 2026

    @hariDasu

    I had to write a customServer instead of using MSW/native and polyfill BroadcastChannel, Event, MessageEvent, and EventChannel.

    In environments I tested in

    1. trpc
    2. axios

    Wondering if using expo/fetch makes this simpler?

    aka less polyfills, probably still need to monkey patch global.fetch for msw interceptor to work

  19. anztrax commented on Mar 28, 2026

    @anztrax

    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 (typeof global.ReadableStream === "undefined") {
      global.ReadableStream = ReadableStream;
    }
    
    if (typeof global.WritableStream === "undefined") {
      global.WritableStream = WritableStream;
    }
    
    if (typeof global.TransformStream === "undefined") {
      global.TransformStream = TransformStream;
    }
    
    if (typeof global.Event === "undefined") {
      global.Event = function Event(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 (typeof global.EventTarget === "undefined") {
      global.EventTarget = function EventTarget() {
        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]) return true;
        this.listeners[event.type].forEach((cb) => cb.call(this, event));
        return !event.defaultPrevented;
      };
    }
    
    if (typeof global.MessageEvent === "undefined") {
      global.MessageEvent = function MessageEvent(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 (typeof BroadcastChannel === "undefined") {
      global.BroadcastChannel = class BroadcastChannel extends global.EventTarget {
        constructor(channelName) {
          super();
          this.channelName = channelName;
          this._subscribers = [];
        }
    
        postMessage(message) {
          const event = new global.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 (typeof global.XMLHttpRequestUpload === 'undefined') {
      global.XMLHttpRequestUpload = function XMLHttpRequestUpload() {};
      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 (typeof global.XMLHttpRequest !== 'undefined') {
      const _getAllResponseHeaders = global.XMLHttpRequest.prototype.getAllResponseHeaders;
      global.XMLHttpRequest.prototype.getAllResponseHeaders = function () {
        return _getAllResponseHeaders.call(this) ?? '';
      };
    }
  20. debitan commented on Apr 24, 2026

    @debitan

    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:

    const nativeFetch = globalThis.fetch;
    try {
      delete globalThis.fetch;
      globalThis.fetch = nativeFetch;
      Object.defineProperty(globalThis, "fetch", {
        value: nativeFetch,
        writable: true,
        configurable: true,
      });
    } catch (error) {
      if (typeof globalThis.fetch === "undefined") {
        globalThis.fetch = nativeFetch;
      }
    }

    Issue 2: Missing Web APIs at import time

    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:

    if (typeof globalThis.Event === "undefined") {
      globalThis.Event = class Event {
        type: string;
        bubbles = false;
        cancelable = false;
        defaultPrevented = false;
        constructor(type: string, init?: { bubbles?: boolean; cancelable?: boolean }) {
          this.type = type;
          this.bubbles = init?.bubbles ?? false;
          this.cancelable = init?.cancelable ?? false;
        }
        preventDefault() { this.defaultPrevented = true; }
        stopPropagation() {}
        stopImmediatePropagation() {}
      };
    }
    
    if (typeof globalThis.EventTarget === "undefined") {
      globalThis.EventTarget = class EventTarget {
        private _listeners: Record<string, Array<(...args: unknown[]) => void>> = {};
        addEventListener(type: string, listener: (...args: unknown[]) => void) {
          (this._listeners[type] ??= []).push(listener);
        }
        removeEventListener(type: string, listener: (...args: unknown[]) => void) {
          const list = this._listeners[type];
          if (list) this._listeners[type] = list.filter((l) => l !== listener);
        }
        dispatchEvent(event: { type: string }) {
          for (const listener of this._listeners[event.type] ?? []) listener(event);
          return true;
        }
      };
    }
    
    if (typeof globalThis.MessageEvent === "undefined") {
      globalThis.MessageEvent = class MessageEvent {
        type: string;
        data: unknown;
        constructor(type: string, init?: { data?: unknown }) {
          this.type = type;
          this.data = init?.data;
        }
      };
    }
    
    if (typeof globalThis.BroadcastChannel === "undefined") {
      globalThis.BroadcastChannel = class BroadcastChannel {
        constructor(_name: string) {}
        postMessage() {}
        close() {}
        addEventListener() {}
        removeEventListener() {}
        dispatchEvent() { return true; }
      };
    }

    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.

  21. added 2 commits that reference this issue on Apr 25, 2026
    936d035
    57d14e5
  22. vladlenskiy commented on Apr 25, 2026

    @vladlenskiy

    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.

  23. kettanaito commented on May 1, 2026

    @kettanaito
    Member

    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-polyfill seems 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:

    const owner = {}
    Object.defineProperty(owner, 'foo', {
      value: 'bar',
      configurable: false,
    })
    delete owner.foo
    
    // TypeError: Cannot delete property 'foo' of #<Object>

    Can you please paste the property descriptor for global fetch in Hermes?

    Object.getOwnPropertyDescriptor(globalThis, 'fetch')

    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.

  24. kettanaito commented on May 1, 2026

    @kettanaito
    Member

    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.

  25. kettanaito commented on May 1, 2026

    @kettanaito
    Member

    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.

  26. coolsoftwaretyler commented on Jul 6, 2026

    @coolsoftwaretyler

    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).

  27. kettanaito commented on Sep 28, 2026

    @kettanaito
    Member

    Released: v3.0.0 🎉

    This has been released in v3.0.0.

    Get these changes by running the following command:

    npm i msw@latest
    

    Predictable release automation by Release.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugneeds:triagescope:node

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions