Msw: Question: Is it possible to mock direct requests using the setupWorker?

Created on 25 Jul 2020  路  3Comments  路  Source: mswjs/msw

Is it possible to do something like this:
https://mswjs.io/docs/getting-started/integrate/node#direct-usage

Using a worker instead of a server?

question

All 3 comments

Hey, @luistak. What do you mean by "direct request"?

If you mean a request to an absolute URL, then of course you can. Both server and client counterpart of MSW have the same support for request URLs. The exception you've mentioned is that in NodeJS one must have absolute request URLs (not the library's limitation).

For example, here's how you mock a response to a GitHub API:

// src/mocks.js
// 1. Import mocking utils.
import { setupWorker, rest } from 'msw'

// 2. Define request handlers and response resolvers.
const worker = setupWorker(
  rest.get('https://github.com/octocat', (req, res, ctx) => {
    return res(
      ctx.delay(1500),
      ctx.status(202, 'Mocked status'),
      ctx.json({
        message: 'Mocked response JSON body',
      }),
    )
  }),
)

// 3. Start the Service Worker.
worker.start()

Let me know if this is what you meant.

Hum...

It really works, but I found a bug using msw withcreate-react-app

If there is a homepage link in your package.json like this: https://www.yourdomain.com/${SOMETHING}

The SOMETHING suffix will be attached to your PUBLIC_URL, then every request won't reach those mocked requests

Hum... just found a bug using create-react-app

If there is a homepage link in your package.json like this: https://www.yourdomain.com/${SOMETHING}

The SOMETHING suffix will be attached to your PUBLIC_URL, then every request won't reach those mocked requests

I fixed it removing the homepage from the script then adding the SOMETHING suffix using cross-env on the build script 馃槃

"build": "cross-env PUBLIC_URL=/SOMETHING/ react-scripts build",
Was this page helpful?
0 / 5 - 0 ratings