Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 67 additions & 9 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
name: ci

on:
push:
branches: [main]
pull_request:
workflow_dispatch:

permissions:
Expand All @@ -11,32 +14,44 @@ jobs:
runs-on: blacksmith-6vcpu-macos-26
timeout-minutes: 25
steps:
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0
- name: Checkout
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0

- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e
- name: Set up pnpm
uses: pnpm/action-setup@0e279bb959325dab635dd2c09392533439d90093
with:
node-version: 24
cache: 'pnpm'
version: 11.26.0

- uses: pnpm/action-setup@0e279bb959325dab635dd2c09392533439d90093
- name: Set up Node.js
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e
with:
version: 11.26.0
node-version: 24
cache: 'pnpm'

- name: Install dependencies
run: pnpm install --frozen-lockfile

- name: Check types
run: pnpm typecheck

- name: Lint
run: pnpm lint

- name: Build
run: pnpm build

# The test app resolves "@msw/react-native" types from the build output.
- name: Check types
run: pnpm typecheck

- name: Validate package
run: pnpm publint

# "pod install --deployment" fails if the CocoaPods version
# differs from the one recorded in the lockfile.
- name: Install CocoaPods
working-directory: test/app/ios
run: |
gem install cocoapods --version "$(awk '/^COCOAPODS:/ { print $2 }' Podfile.lock)" --no-document
pod --version

- name: Install iOS pods
working-directory: test/app/ios
run: pod install --deployment
Expand All @@ -54,3 +69,46 @@ jobs:
name: native-test-results
path: test/app/.harness/results.json
if-no-files-found: ignore

release:
needs: [test]
if: github.ref == 'refs/heads/main'
# npm accepts provenance attestations only from GitHub-hosted runners,
# so the publish job must not run on Blacksmith.
runs-on: ubuntu-latest
concurrency:
group: release
cancel-in-progress: false
permissions:
contents: read
id-token: write
steps:
- name: Checkout
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0
with:
fetch-depth: 0
token: ${{ secrets.GH_ADMIN_TOKEN }}

- name: Set up pnpm
uses: pnpm/action-setup@0e279bb959325dab635dd2c09392533439d90093
with:
version: 11.26.0

- name: Set up Node.js
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e
with:
# Trusted Publishing only works on Node.js v24.
node-version: 24

- name: Setup Git
run: |
git config --local user.name "Artem Zakharchenko"
git config --local user.email "kettanaito@gmail.com"

- name: Install dependencies
run: pnpm install --frozen-lockfile

- name: Release
run: pnpm release
env:
GITHUB_TOKEN: ${{ secrets.GH_ADMIN_TOKEN }}
117 changes: 6 additions & 111 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# @msw/react-native
# `@msw/react-native`

Mock Service Worker integration for React Native.

```sh
pnpm add -D @msw/react-native msw
npm i -D @msw/react-native msw
```

```ts
Expand All @@ -19,114 +19,9 @@ network.use(
network.enable()
```

The exported `network` is the object returned by MSW’s `defineNetwork()`, configured
for React Native. Use `network.enable()` / `network.disable()` for interception,
`network.configure()` before enabling to set initial handlers and options, and
`network.use()`, `network.resetHandlers()`, and `network.restoreHandlers()` to
manage handlers. Handler APIs remain in the `msw` peer dependency.
> Make sure to import `@msw/react-native` before `msw` as it installs necessary polyfills, like the one for `URL`, that are required for `msw` to function.

Import `@msw/react-native` before `msw`. The library installs its URL, text encoding,
and Web Streams dependencies and exposes React Native’s existing `MessageEvent`
globally before initializing its integration. Only missing APIs are installed;
existing runtime implementations are preserved. No application polyfill setup is
required for these APIs. Fetch body compatibility remains unresolved; see below.
## Documentation

## Development

Use Node.js 24 (see `.node-version`). Both workspace packages use TypeScript 7.0.
Declarations are emitted by `tsc` directly because tsup’s declaration bundler
requires the old JavaScript compiler API.

MSW is installed as a development dependency. Run:

```sh
pnpm install
pnpm build
pnpm typecheck
pnpm lint
pnpm publint
```

MSW 2.15.0 has an incompatible `InterceptorSource` constructor type. The correction
in MSW must be released before this package’s type checks can pass against the
registry dependency.

## Native integration tests

`test/app` is a React Native Community CLI app. React Native Harness bundles the
tests with Metro and executes them in Hermes on an iOS simulator:

```text
pnpm test → Harness → Metro → iOS app → fetch / XMLHttpRequest → MSW
```

Requires macOS, Xcode with an installed iPhone simulator, and CocoaPods.
After installing dependencies and building this package:

```sh
(cd test/app/ios && pod install)
pnpm test:build:ios
pnpm test
```

The build command builds and installs the debug app on the first available iPhone
simulator. Set `IOS_SIMULATOR` and/or `IOS_VERSION` for both commands to select a
specific installed simulator. Native rebuilds are only needed when native
sources or dependencies change; Metro picks up JavaScript changes on each run.

The suite covers initial fetch handling, `network.use()`, `network.resetHandlers()`,
and XMLHttpRequest handling. No networking or native modules are mocked by the
runner. The library supplies the Web API polyfills; the fixture has no polyfill setup.

CI runs lint, builds, type checks, publint, and these native tests on macOS.

### Native runtime compatibility

The custom Fetch body adapter has been removed. With React Native 0.87.1 and
linked MSW, the iOS suite currently reports **9 failed, 10 passed**. Request and
Response constructors lack standard body streams, and mocked response payloads
are lost. Existing tests expose these failures without skips.

See [Fetch compatibility findings](docs/fetch-compatibility.md) for the reproduced
gaps and evaluated alternatives. The library does not replace Request/Response.

MSW defers `BroadcastChannel` creation until WebSocket usage. The library exposes
React Native's existing `XMLHttpRequestUpload` and `ProgressEvent` implementations
only when their globals are missing.

Native test results are written to `test/app/.harness/results.json` and uploaded
as a CI artifact.

For local MSW verification, link both workspace consumers to the built MSW
checkout, then run `pnpm test`. Metro automatically watches the resolved MSW
package directory, including local links. CI uses the registry dependency and
needs the MSW fixes released.


## Module format

The package ships ESM only. Both `main` and the `default` export condition point
to `lib/index.js`, allowing Metro to resolve the same file for `import` and
`require` without an import-only exports branch.

```text
import / require → lib/index.js (ESM) → Metro transform → Hermes
```

Modern React Native’s Babel preset supports ESM syntax out of the box. Package
exports are enabled by default in Metro 0.82 / React Native 0.79 and Expo SDK 53.
See [Metro’s module API](https://metrobundler.dev/docs/module-api/),
[Metro’s exports guide](https://metrobundler.dev/docs/package-exports/), and
[Expo’s resolution guide](https://docs.expo.dev/versions/latest/config/metro/#es-module-resolution).

Verified with React Native 0.87.1 / Metro 0.87: static `import` and `require`
resolve to the same export on the iOS simulator; Android bundling also succeeds.
The entry now initializes React Native polyfills and requires Metro’s React Native
transforms; it is not directly executable in plain Node. This does not promise support
for every older Node/Jest setup; those may need ESM-aware configuration or
dependency transforms. Keep `import.meta` and top-level await out of the native
entry, since accepting ESM syntax does not imply support for every ESM feature.

A dynamic-import probe failed for both this package and React itself under
Harness 1.4.1. Dynamic import has not been independently verified in the native
app; that runner limitation is separate from the passing static-import check.
- [React Native guide for MSW](https://mswjs.io/guides/integrations/react-native)
- [MSW documentation](https://mswjs.io/docs/)
74 changes: 52 additions & 22 deletions docs/fetch-compatibility.md
Original file line number Diff line number Diff line change
@@ -1,40 +1,70 @@
# Fetch compatibility findings
# Fetch compatibility

Investigated 2026-09-09. Removed `src/compat/fetch-body.ts`; no replacement installed.
No suitable drop-in found among the candidates below.
Last updated 2026-11-18. Verified against React Native 0.87.1 on iOS (Hermes).

React Native 0.87.1 uses `whatwg-fetch` 3.6.20. Adding `ReadableStream` alone does
not give its Request/Response constructors stream support. Reproduced in Hermes:
React Native 0.87.1 uses `whatwg-fetch` 3.6.20, built on top of XMLHttpRequest.
Its Request/Response have no body streams, and adding `ReadableStream` alone
does not change that:

```ts
new Response('hello').body // undefined
new Request('https://msw.test', { method: 'POST', body: 'hello' }).body // undefined
await new Response(stream).text() // "[object ReadableStream]", not the stream contents
```

The last expression requires suppressing RN's TypeScript error: its declarations
also exclude stream input. Ordinary string-body readers and clones still work.
Stream consumption tracking and independent stream clones cannot work without a
body stream. [Fetch implementation](https://github.com/JakeChampion/fetch/blob/v3.6.20/fetch.js).
[Fetch implementation](https://github.com/JakeChampion/fetch/blob/v3.6.20/fetch.js),
[upstream issue](https://github.com/facebook/react-native/issues/27741).

```text
HttpResponse.json(data) → RN Response → .body is undefined
→ interceptor reconstructs response → empty payload
```
## Why MSW needs body streams

| Scenario | Without body streams (`@mswjs/interceptors` 0.45.12) |
| --- | --- |
| Mocked `fetch` responses | Work. The mocked response is forwarded as-is. |
| Mocked `XMLHttpRequest` responses | Empty body. The interceptor reads `response.body.getReader()` and treats a missing body as empty. |
| Mocked stream responses (`new Response(stream)`, SSE) | Broken. The stream is coerced to a string. |

## Solution

`src/polyfills/fetch-body.js` adds the body stream semantics to React Native's
Request/Response in place, by patching their prototypes. The classes are not
replaced, so every instance keeps its identity, including the responses created
by the native `fetch`.

- `body` returns a lazy `ReadableStream` (`null` if there is no body).
Nothing is read from the body until the stream is read.
- A `ReadableStream` is accepted as the body, and `text()`, `arrayBuffer()`,
and `json()` read it.
- `bodyUsed` is set once the stream is read.
- `clone()` tees stream bodies.
- `fetch` buffers the stream body of an outgoing request before passing it
to React Native.

Interceptors reads `rawResponse.body` when constructing mocked Fetch responses.
This breaks ordinary JSON mocks, not just applications requesting streaming.
The existing iOS suite after removal: **9 failed, 10 passed** (4 suites).
The polyfill relies on the private fields of `whatwg-fetch` (`_initBody`,
`_bodyInit`, `_noBody`, etc.). It does nothing if the global classes do not look
like `whatwg-fetch` or already implement `body`.

This replaces the removed `src/compat/fetch-body.ts`, which reimplemented
the body model instead of augmenting the existing one.

## Limitations

- **No true network streaming.** React Native buffers the bodies of the actual
responses, so they are exposed as a single chunk. Incremental delivery requires
native code. Mocked responses are produced in JavaScript and stream as written.
- `blob()` rejects for stream bodies. React Native cannot create a Blob from
binary data.
- `FormData` bodies cannot be read as a stream.
- Outgoing stream bodies are buffered in full before the request is sent.

## Alternatives considered

| Candidate | Finding |
| --- | --- |
| `react-native-fetch-api` 3.0.0 | Published constructor probes: Request has no `.body`; string Response streams immediately end; byte streams yield numbers, not Uint8Array chunks; stream clones share the same stream. Not suitable. [Body](https://github.com/react-native-community/fetch/blob/master/src/Body.js), [Response](https://github.com/react-native-community/fetch/blob/master/src/Response.js). |
| `react-native-fetch-api` 3.0.0 | Published constructor probes: Request has no `.body`; string Response streams immediately end; byte streams yield numbers, not Uint8Array chunks; stream clones share the same stream. Text-only network streaming. Not suitable. [Body](https://github.com/react-native-community/fetch/blob/master/src/Body.js), [Response](https://github.com/react-native-community/fetch/blob/master/src/Response.js). |
| `expo/fetch` (Expo 57.0.21) | Maintained native streaming transport, but runtime installs `fetch`, retaining RN Request/Response constructors. Its implementation explicitly notes the missing Request implementation. Requires Expo native infrastructure; not a constructor replacement. [Runtime](https://github.com/expo/expo/blob/main/packages/expo/src/winter/runtime.native.ts), [Fetch](https://github.com/expo/expo/blob/main/packages/expo/src/winter/fetch/fetch.ts). |
| `@whatwg-node/fetch` 0.10.13 | Browser entry re-exports existing globals; alternate implementation targets Node. Does not supply RN body support. [Package](https://github.com/ardatan/whatwg-node/tree/master/packages/fetch). |
| `react-native-nitro-fetch` | Native streaming transport. Requires native modules; not evaluated further. [Repository](https://github.com/margelo/react-native-nitro-fetch). |
| Reading `response.arrayBuffer()` in the XMLHttpRequest interceptor when `body` is missing | Fixes mocked XMLHttpRequest responses only. Mocked stream responses stay broken. |

Candidate probes ran against published JavaScript in Node; Expo was source-reviewed,
not installed or tested in the native app. RN failures were verified on iOS.

A durable fix belongs in a maintained Fetch implementation with complete body
semantics, or a separately scoped change to Interceptors' transport requirements.
The removed module effectively reimplemented that body model inside MSW.
not installed or tested in the native app.
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"prepack": "pnpm build",
"lint": "oxlint src test/app/tests test/app/scripts test/app/*.js test/app/*.mjs *.ts",
"publint": "publint",
"test:build:ios": "pnpm --dir test/app build:ios"
"test:build:ios": "pnpm --dir test/app build:ios",
"release": "release publish"
},
"main": "./lib/index.js",
"module": "./lib/index.js",
Expand Down Expand Up @@ -68,6 +69,7 @@
"web-streams-polyfill": "^4.5.1"
},
"devDependencies": {
"@ossjs/release": "^0.11.2",
"@types/node": "^24.0.0",
"msw": "^3.0.6",
"oxlint": "^1.94.0",
Expand Down
Loading
Loading