mswjs / msw

Industry standard API mocking for JavaScript.
https://mswjs.io
MIT License
16k stars 522 forks source link

Always results in Network Error when using undici 6.x #2172

Closed SharmaTushar closed 4 months ago

SharmaTushar commented 5 months ago

Prerequisites

Environment check

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.

TheHolyWaffle commented 5 months ago

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

kettanaito commented 4 months ago

@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:

kettanaito commented 4 months ago

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