Skip to content

Does it allow for mocking on demand? #955

Answered by kettanaito
adammo94 asked this question in Q&A
Discussion options

You must be logged in to vote

Hey, @adammo94.

You can control whether mocking is enabled on runtime by starting or stopping the worker whenever you need.

Here's how I'd implement an on-demand mocking as you described:

// mocks/browser.js
import { setupWorker } from 'msw'
import { handlers } from './your-handlers'

// Create the worker instance but don't start it yet.
// This means that the mocking is configured but not active.
export const worker = setupWorker(...handlers)
// ui.js
import { worker } from './mocks/browser'

btn.addEventListener('click', () => {
  // Start the worker to enable requests interception.
  worker.start()
})

Note that calling worker.start() returns a Promise. Y…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@kettanaito
Comment options

Answer selected by kettanaito
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants