question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Guidance on a dev flow that switches between mocked responses and real ones

See original GitHub issue

Is your feature request related to a problem? Please describe. In my practice, I often switch my dev setup between hitting the real API (for correctness testing) and using the MockServiceWorker for its faster and easier to control response.

My current approach in a create-react-app project is this:

if (process.env.NODE_ENV === 'development' && process.env.REACT_APP_MOCK_API === 1) {
    require('./__api_mocks__')
}

However, switching between mocked and non-mocked responses requires switching the ENV variable and restarting the webpack process.

Describe the solution you’d like Maybe an interface on localStorage could be exposed to control msw behavior. Possibly something like:

// disable
localStorage.msw = false

// enable
localStorage.msw = undefined | true

// mock only requests matching urls like "products/list" by providing a regex
localStorage.msw = /products\/list/

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:7 (7 by maintainers)

github_iconTop GitHub Comments

6reactions
VanTanevcommented, May 5, 2020

@kettanaito Using your code as a base, I added only a couple of small fixes (eg, worker.stop() doesn’t return a promise. Also, I wanted to have a way to specify default options).

Thanks a lot for your assistance! Hopefully, this is useful for other people too.

import { setupWorker } from 'msw'
import characterMocks from './character'

const worker = setupWorker(...characterMocks)

// necessary for history-based routing
const options = { serviceWorker: { url: '/mockServiceWorker.js' } }
weakStart(worker, options)

/////////////////////////////////

const FLAG = 'msw-suppressed'
type StartOptions = Parameters<typeof worker.start>[0]

export function weakStart(
    worker: ReturnType<typeof setupWorker>,
    defaultOptions: StartOptions = {},
): ReturnType<typeof worker.start> {
    const start = (options?: StartOptions): ReturnType<typeof worker.start> => {
        // Check the current mocking state in the localStorage
        const shouldSuppress = localStorage.getItem(FLAG)

        if (shouldSuppress) {
            return Promise.resolve(null)
        }

        return worker.start(options ?? defaultOptions)
    }

    // Make controller methods globally available to call during runtime.
    // Chain the localStorage update to preserve the state.
    const mocks = {
        start: (options?: StartOptions) =>
            start(options ?? defaultOptions).then(() =>
                localStorage.removeItem(FLAG),
            ),
        stop: () => {
            worker.stop()
            localStorage.setItem(FLAG, 'true')
        },
    }
    ;(window as any).mocks = mocks

    // Enable mocks by default
    return start(defaultOptions)
}
0reactions
kettanaitocommented, May 5, 2020

My pleasure! True, stop() at the moment doesn’t return a Promise. It used to unregister the worker, but now the worker unregisters itself when the last controlled client is closed. stop() now stops the mocking, removing the client’s id from the worker’s internal list of clients.

Glad it helped!

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to Mock API Requests in Front-End Development? - Codit
Let's look at a high-level diagram of MSW's request flow: You'll need to write declarative request handlers to capture your requests, as well ......
Read more >
Mocking | Guide - Vitest
A blazing fast unit test framework powered by Vite.
Read more >
Python Mocking 101: Fake It Before You Make It - Fugue
This post was written by Mike Lin. Welcome to a guide to the basics of mocking in Python. It was born out of...
Read more >
Stubbing and Mocking in Java with the Spock Testing ...
Learn how to create true Java unit tests by mocking all external dependencies in your unit tests with the Spock testing framework.
Read more >
Mocking is a Code Smell - Medium
One of the biggest complaints I hear about TDD and unit tests is that people struggle with all of the mocking required to...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found