Deferred mounting
Service Worker registration is an asynchronous process, which means that any requests that happen between calling worker.start()
and the worker registration cannot be intercepted by the library.
To tackle this, Mock Service Worker captures all outgoing requests in that pending period and defers their execution until the worker registration has finished, and the worker is ready to handle requests.
Learn more about the
waitUntilReady
option.
However, in case when such default behavior is insufficient or undesired, you may defer your application's mount manually. Since worker.start()
returns a Promise
, you can execute your application bootstrapping logic once that promise resolves.
Here's an example on how to defer application's mount in a React application:
1// src/index.js2import React from 'react'3import ReactDOM from 'react-dom'4import App from './App'56function prepare() {7 if (process.env.NODE_ENV === 'development') {8 const { worker } = require('./mocks/browser')9 return worker.start()10 }1112 return Promise.resolve()13}1415prepare().then(() => {16 ReactDOM.render(<App />, document.getElementById('root'))17})