Is there a recommended way to mock fetch? #11169
Replies: 4 comments 6 replies
-
I wouldn't call it "recommended" but this seems to work: import { afterEach, mock } from "bun:test"
export const mockFetch = mock()
global.fetch = mockFetch
mock.module("node-fetch", () => mockFetch)
afterEach(() => {
mockFetch.mockReset()
}) Then in a test file: import { mockFetch } from "./mock-fetch-preload"
test("Fetch gets mocked again", async () => {
mockFetch.mockReturnValueOnce(Promise.resolve(new Response("hello world")))
const response = await <some function that calls fetch>
expect(mockFetch).toHaveBeenCalledTimes(1)
expect(mockFetch).toHaveBeenCalledWith(...)
//etc
}) It needs to be run with |
Beta Was this translation helpful? Give feedback.
-
This gives hope there is something better but I guess not built in... I did just come across bun-bagel which sounds promising and I'm going to try out. |
Beta Was this translation helpful? Give feedback.
-
Msw |
Beta Was this translation helpful? Give feedback.
-
For future googlers. I found bun-bagel to be buggy and feature incomplete. This worked better for me: |
Beta Was this translation helpful? Give feedback.
-
I've got a (bun + hono) api that interacts with several different REST APIs. Some of those APIs are easy to test; I control the code that calls fetch and can mock it sanely. But others are using SDKs that call fetch on my behalf (sometimes the global fetch, other times node-fetch).
Is there a good way to reliably mock fetch in these third-party projects? I can mock the individual SDK callsites if I have to, but it would be easier to mock fetch. I've tried several incantations of
mock.module
and even settingglobal.fetch = mock()
, but haven't had much luck.Beta Was this translation helpful? Give feedback.
All reactions