LOGOMock Service Worker
  1. Recipes
  2. Deferred mounting

Deferred mounting

This is not a default recommended setup. Please refer to the default browser integration, and use this recipe only when the default setup doesn't cover your needs.

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.js
2import React from 'react'
3import ReactDOM from 'react-dom'
4import App from './App'
5
6function prepare() {
7 if (process.env.NODE_ENV === 'development') {
8 const { worker } = require('./mocks/browser')
9 return worker.start()
10 }
11
12 return Promise.resolve()
13}
14
15prepare().then(() => {
16 ReactDOM.render(<App />, document.getElementById('root'))
17})