Mock Service Worker

React Native

Pre-requisites

URL polyfill

The URL class in React Native is not fully compliant with the URL specification. This may lead to all sorts of unexpected behavior, as Mock Service Worker creates and operates with URL instances on runtime.

Use a specification-compliant URL class polyfill

Here are some of the recommended polyfills:

Configure server

Let's create a file in our mock definition directory (src/mocks) where we would configure our request mocking server.

Create a src/mocks/server.js file

1$ touch src/mocks/server.js

In the server.js file we are going to create a server instance with our request handlers defined earlier.

Import setupServer function from the msw/native package and create a server instance with the previously defined request handlers

1// src/mocks/server.js
2import { setupServer } from 'msw/native'
3import { handlers } from './handlers'
4
5// This configures a request mocking server with the given request handlers.
6export const server = setupServer(...handlers)

Setup

Runtime

Explain how to use MSW for development.

Testing

  • Repeat NodeJS setup.