Mocking fetch with Jest for a Cloudlare Worker

Hi all - i'm trying to figure out something that potentially could be very simple. I've got a Worker running on Cloudflare that pulls data from an external API, via fetch. Inside my 'fetchData.ts' I have the following.
const response = await fetch(env.ENDPOINT, {
method: "POST",
headers: {
Authorization: `Basic ${btoa(
`someKey`
)}]`,
"Content-Type": "application/x-www-form-urlencoded"
},
body: "someBody"
});
const response = await fetch(env.ENDPOINT, {
method: "POST",
headers: {
Authorization: `Basic ${btoa(
`someKey`
)}]`,
"Content-Type": "application/x-www-form-urlencoded"
},
body: "someBody"
});
I'm trying to write a 'testData.test.ts' file to check that fetch was called with the correct args. If I was working with a node environment i'd just mock out node-fetch and check what the mock was called with. With the worker, fetch is global, so I have no idea what to mock. Any help with this would be much appreciated
2 Replies
MrBBot
MrBBot•6mo ago
Hey! 👋 You should be able to use jest.spyOn(globalThis, "fetch") to get a mock function. Can I also check how you're running your tests? Are you using jest-environment-miniflare, or something else?
jpbrown84
jpbrown84•6mo ago
Thanks 🙂 I'm just using jest with "test": "npx jest", I've now got a version of this working using miniflare, thanks again