msw icon indicating copy to clipboard operation
msw copied to clipboard

Always results in Network Error when using undici 6.x

Open SharmaTushar opened this issue 1 year ago • 1 comments

Prerequisites

Environment check

  • [X] I'm using the latest msw version
  • [X] I'm using Node.js version 18 or higher

Node.js version

v20.13.1

Reproduction repository

https://github.com/SharmaTushar/msw-undici-network-error

Reproduction steps

npm run test

Current behavior

The requests are correctly intercepted by msw but trying to return a response results in Network Error. Can be fixed by falling back to undici v5.

Expected behavior

Should not throw error when trying to return success response.
Would be good to advise sticking to undici v5 in docs if msw is not yet compatible with it.

SharmaTushar avatar Jun 03 '24 16:06 SharmaTushar

Your title/description mentions undici but the minimal reproduction uses axios?

TheHolyWaffle avatar Jun 06 '24 17:06 TheHolyWaffle

@SharmaTushar, thanks for raising this.

Undici v6 depends on structuredClone(), which is broken in Jest (transitively through the dependency on core-js). You cannot use Undici v6 with Jest. This is not specific to MSW.

Solution 1: Switch to Vitest + HappyDOM

Vitest and HappyDOM provide a far better experience when it comes to respecting the standards. I highly encourage you to consider them. The API is compatible between Jest/JSDOM, and the gains you get are worth it tenfold.

Solution 2: Downgrade to Undici v5

Downgrade to v5 of Undici that doesn't rely on structuredClone(). That will fix the underlying issue.

More info

Here are some links if you want to learn more about this issue:

  • https://github.com/mswjs/msw/issues/1931#issuecomment-1890461324
  • https://github.com/mswjs/msw/issues/1929#issuecomment-1908535966
  • https://github.com/mswjs/msw/issues/1916#issuecomment-19085449463

kettanaito avatar Jul 12 '24 09:07 kettanaito

@TheHolyWaffle, that's okay. Undici is used as polyfill for the Fetch API, which Jest/JSDOM take away from you entirely.

kettanaito avatar Jul 12 '24 09:07 kettanaito