Skip to content

Usage with MSW / patched fetch #295

@meesvandongen

Description

@meesvandongen

Environment

Node

Reproduction

https://codesandbox.io/p/sandbox/stoic-https-6gjdtz?file=/index.js:14,16

import { setupServer } from "msw/node";
import { http, HttpResponse } from "msw";
import wretch from 'wretch'
import { ofetch, fetch, createFetch } from 'ofetch'
import got from 'got'

const server = setupServer(
    http.get('https://example.com', () => {
        return HttpResponse.text('1')
    })
)
server.listen();

console.table([
 ['fetch', await globalThis.fetch('https://example.com').then(res => res.text()).then(res => res === '1')],
 ['ofetch fetch', await fetch('https://example.com').then(res => res.text()).then(res => res === '1')],
 ['ofetch createFetch', await createFetch()('https://example.com').then(res => res === '1')],
 ['ofetch', await ofetch('https://example.com').then(res => res === '1')],
 ['wretch', await wretch('https://example.com').get().text().then(res => res === '1')],
 ['got', await got.get('https://example.com').text().then(res => res === '1')],
])

CleanShot 2023-12-23 at 14 00 06@2x

Describe the bug

When other tools patch fetch, the global instance of ofetch will have the original fetch instance. This will cause tools such as msw to not be able to intercept requests with ofetch. A workaround could be to only get the globalThis.fetch at request time if no other fetch is specified.

Additional context

Users can work around this at this time by using the createFetch helper function.

Logs

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions