Is there a recommended way to mock fetch? #11169
Unanswered
dusty-phillips
asked this question in
Q&A
Replies: 2 comments 1 reply
-
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.
0 replies
-
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.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
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