Replies: 1 comment
-
Userland solution (fetch only): const mockFetch = <T = unknown>(
spy: Mock<typeof fetch>,
url: string,
data: T,
options: ResponseInit = { status: 200 }
) => {
const fn = (requestUrl: URL | RequestInfo) =>
requestUrl === url
? Promise.resolve(new Response(JSON.stringify(data), options))
: Promise.resolve(new Response('Not Found', { status: 404 }));
fn.preconnect = () => {};
return spy.mockImplementationOnce(fn);
}; |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
This is a suggestion to add a new spyOn method https://bun.sh/docs/test/mocks#spyon.
This would allow developers to mock functions based on specific arguments or paths.
This would be particularly useful for mocking
fetch
calls but could be useful elsewhere.Currently this is done by using
spy.mockImplementation()
to overwrite the function and check the parameters orspy.mockResolvedValue()
. The downside ofmockImplementation
is that it requires boilerplate. The downside ofmockResolvedValue
is that it will fire regardless of the arguments.There is no related API in jest or vitest as far as I could tell. It is just something I am hoping for :)
Example:
Example using
mockImplementationOnce
Alternative name:
withArgs
Beta Was this translation helpful? Give feedback.
All reactions