Skip to content

How do you mock different responses in real life? #1117

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

You must be logged in to vote

Hey, @antoinerey. Thanks for raising this, it's a great question.

One great thing is that the handlers you write are still regular JavaScript code executed on the client. This means they have the entire client context, not only the intercepted request. I've seen a great pattern where developers controlled what API responses MSW returns by using the URL query parameters:

export const handlers = [
  rest.get('/api/articles/latest', (request, response, context) => {
    const pageParams = new URLSearchParams(window.location.search)
    const scenario = pageParams.get('scenario')

    // Sad path
    if (scenario === 'error') {
      return response(
        context.status(500),
        context.

Replies: 7 comments 25 replies

Comment options

You must be logged in to vote
11 replies
@kettanaito
Comment options

@sunpietro
Comment options

@kettanaito
Comment options

@yaswanthmaddula-sureify
Comment options

@kettanaito
Comment options

Answer selected by kettanaito
Comment options

You must be logged in to vote
7 replies
@fvanwijk
Comment options

@fvanwijk
Comment options

@kettanaito
Comment options

@fvanwijk
Comment options

@kettanaito
Comment options

Comment options

You must be logged in to vote
2 replies
@kettanaito
Comment options

@SSERVOUZE
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

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

Comment options

You must be logged in to vote
3 replies
@kettanaito
Comment options

@Bram-Zijp
Comment options

@Bram-Zijp
Comment options

Comment options

You must be logged in to vote
1 reply
@Bram-Zijp
Comment options

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