mswjs / mswjs.io

Official website and documentation for the Mock Service Worker library.
https://mswjs.io
151 stars 177 forks source link

Documentation missing on how to integrate with Expo App Router #372

Open joao-arau-symphony opened 6 months ago

joao-arau-symphony commented 6 months ago

As of today, The React Native integration documentation recommends delaying application initialization until the mocks are loaded like so:

enableMocking().then(() => {
  AppRegistry.registerComponent(appName, () => App)
})

However when using Expo App router the entry point of the application is internal to the library and not available to freely configure.

For apps using App Router, Expo recommends placing initialization code in the RootLayout file instead, but it would be helpful if there is an official recommendation from MSW on how avoid potential race conditions related to app initialization.

sargentieri commented 6 months ago

Do you have a working example of MSW with expo by chance?

uroge commented 3 months ago

index.js file is where you set the entry for expo-router. Instead of importing "expo-router/entry" you could set the entry point manually, and ensure that mocking is enabled:

import { registerRootComponent } from 'expo';
import { ExpoRoot } from 'expo-router';

export const App = () => {
  const ctx = require.context('./src/app');

  return <ExpoRoot context={ctx} />;
};

async function enableMocking() {
  if (!__DEV__) {
    return;
  }

  await import('./msw.polyfills');
  const { server } = await import('./src/server');

  server.listen();
}

enableMocking().then(() => {
  registerRootComponent(App);
});