msw icon indicating copy to clipboard operation
msw copied to clipboard

Can't match the handler in tests in nuxt 3 app using useFetch composable

Open andreimakushkin 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.11.1

Reproduction repository

https://github.com/andreimakushkin/nuxt3-msw

Reproduction steps

I've created an Example vue component with test for it, the component use useFetch composable to call an API, but it doesn't work in test. The test just fails without any errors. MSW server doesn't intercept the call.

In order to run test, use command npm run test

await useFetch('/api/example'); // Doesn't match the handler
await useFetch('api/example'); // Matches the handler, but the app doesn't work

Current behavior

await useFetch('/api/example'); // Doesn't match the msw handler

Expected behavior

await useFetch('/api/example'); // Should match the msw handler

andreimakushkin avatar Jul 23 '24 11:07 andreimakushkin

@andreimakushkin Hello, I have created a Nuxt module called nuxt-msw which should be able to address the issue you mentioned.

shunnNet avatar Aug 30 '24 14:08 shunnNet

This doesn't seem to be an MSW issue but rather a Nuxt issue (or even an intended behavior).

If you take a look at the useFetch hook, it doesn't use globalThis.fetch anywhere:

// node_modules/nuxt/dist/app/composables/fetch.js
let _$fetch = opts.$fetch || globalThis.$fetch;

console.log('using native fetch?', _$fetch === globalThis.fetch

That check will be false. Nuxt seems to be using a custom $fetch function for test purposes, which you can also see if you inspect it:

console.log(_$fetch)

[AsyncFunction: $fetch2] {
  raw: [AsyncFunction: $fetchRaw2],
  native: [Function (anonymous)],
  create: [Function (anonymous)]
}

This is not fetch from Node.js. Respectively, MSW won't support this.

I suggest you raise this in Nuxt repo.

kettanaito avatar Nov 13 '24 21:11 kettanaito