MSW server cannot run properly with Expo.

Hello folks! I’m facing an issue with MSW. As I have to run Redux RTK Query Rest API and call some endpoint, I need to mock REST Api.

I got to use MSW following an example from redux-toolkit repository and as it does support React Native.

Now, using SDK 45, managed workflow, I run the app but nothing happens.

This is a link to my git repo. :point_left:

Question: Wait ! How to reproduce the issue? :sweat_smile:
Answer: After installing deps, just run the app with expo start, you’ll have a bottom tab navigator with exactly 2 tabs. When you press on tab 2 (on the right) you must see “loading…” text. Which means an api call is in progress, then nothing.:worried:

NOTE: If you think MSW isn’t good with Expo, then what do you suggest instead?!

thanks in advance

“Service Worker API” is a construct that is standardized in browsers.

A React-Native/Expo native app, from my understanding, does not have a “Service Worker” construct [though I’m happy to be corrected].

[EDIT]

@iga-frg pointed out that there does appear to be an enhancement to MSW to support RN. Will be interesting to see if this actually works.

There is an RN example, but the MSW docs don’t seem to tout the capability at all?

2 Likes

Hey! I’m glad to tell you “I’ve FOUND IT it WORKs” :rofl: :

I don’t know really what just happened? (I’m still checking what did I touched exactly).

You can find the working example on my same repository entitled: “Commit 5…”.

Usage:
server file:

import { setupServer } from 'msw/native'
import { handlers } from './mockServerHandlers'

const server = setupServer(...handlers);

export default server;

App.tsx:

import "react-native-url-polyfill/auto";
import server from "@app/tests/mock-server";

server.listen({onUnhandledRequest:"bypass"});

Now the app is running and I get mock-api data! :heavy_check_mark:

I hope this will help the community as well, thanks for answering. :raised_hands:

2 Likes

Hello! I’ve made a standalone git repo in order with a good minimal example to show how to use msw properly with Expo.

It could become something cool later :grin:

Link: GitHub - firas1220/expo-msw: A repository to maintain mock-api using msw within Expo app!

2 Likes