MSW Doesn't Seem to Intercept Rest API GET Request When Upgrading to 2.0.1

1.1k views Asked by At

I have something like this in my MSW 1.3.* version and it is working as expected.

const server = setupServer(
  rest.get(
    'http://localhost:1800/users_info',
    (req, res, ctx) => {
      return res(
        ctx.json({
          userId: 123,
        })
      );
    }
  )
);

When upgrading to MSW 2.0.1, I had to update to something like this

const server = setupServer(
  http.get(
    'http://localhost:1800/users_info',
    ({ request, params, cookies }) => {
      return HttpResponse.json({
        userId: 123,
      });
    }
  ),
thrown: HttpError {
      "attempt": undefined,
      "description": "HTTP request failed.  Request was to URL http://localhost:1800/users_info but the error was an unexpected exception \"TypeError: Failed to fetch\"",
      "error": [TypeError: Failed to fetch],
      "request": Object {
        ...
      },
      "status": 0,
      "willRetry": undefined,
    }

but it appears on running my jest test that it isn't getting registered and intercepted. Does anyone know why that would be?

Tried downgrading back to v1 and it works, but want to use v2 now

1

There are 1 answers

0
Josh Kelley On

Since you're using Jest, I'm assuming that you're using jsdom (to test browser-side code) and a fetch polyfill such as whatwg-fetch.

MSW 1 supported various fetch implementations and polyfills, but MSW2 is a significant change: it only supports Node's built-in fetch.

Because of this and other changes, I'm not sure that MSW 2 is a great fit for Jest projects. If you want to upgrade, there are various ways of configuring Jest to use Node's built-in fetch; here are the official recommendations from their migration guide:

  1. Remove your existing fetch polyfill.
  2. Create a jest.polyfills.js file:
const { TextEncoder, TextDecoder } = require('node:util')
 
Reflect.set(globalThis, 'TextEncoder', TextEncoder)
Reflect.set(globalThis, 'TextDecoder', TextDecoder)
 
const { Blob } = require('node:buffer')
const { fetch, Request, Response, Headers, FormData } = require('undici')
 
Reflect.set(globalThis, 'fetch', fetch)
Reflect.set(globalThis, 'Blob', Blob)
Reflect.set(globalThis, 'Request', Request)
Reflect.set(globalThis, 'Response', Response)
Reflect.set(globalThis, 'Headers', Headers)
Reflect.set(globalThis, 'FormData', FormData)
  1. Configure it within your jest.config.js:
module.exports = {
  setupFiles: ['./jest.polyfills.js'],
}