miniflare: API mocking with MSW fails after upgrade to miniflare 2.2.0
Hey @mrbbot, thanks for all the work on miniflare, it’s been a game-changer!
With miniflare 1, I’ve been using mock service worker to mock API responses. When attempting to upgrade to miniflare 2.2.0, my tests failed. I’ve no idea where to start looking for a solution, so I’ve put up a fairly minimal demo, hoping that’ll make it easier to pinpoint the cause. HEAD is using miniflare 2.2.0, while the miniflare-1.4.1 branch shows what it looks like when it’s working. Running npm test should show failing tests for HEAD and passing for the latter.
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Comments: 19 (2 by maintainers)
Hey @SupremeTechnopriest! 👋 Unfortunately, you won’t be able to use
setGlobalDispatcherinsidejest-environment-miniflare. Miniflare’sundiciversion is imported outside the Jest environment in Node. Jest and Node don’t share a module cache, so trying to importundiciinside Jest will always give you a different version.Currently, I think the best option for
jest-environment-miniflareis to use Jest’s function mocks to mock the globalfetchfunction. Something like… (untested 😅)I’d definitiely like to start a discussion on this though. Maybe a global API like
getMiniflareMockAgent()that returned a correctly-setupMockAgent?@SupremeTechnopriest and @LukePammant, I can confirm that mocking the
globalThis.fetchdoesn’t work withminiflare.dispatchFetch. We have somefetch()calls to some external APIs inside our worker, we wanted to test those calls, but spying fetch was not possible. We used this library to workaround. We start a local HTTP server and use this server instead of external APIs.I was hoping that perhaps this issue had been resolved with the release of 2.4.0 yesterday, but it has been postponed to 2.5.0. I am very much looking forward to the next release 👀
This was super helpful to me, as jest-fetch-mock doesn’t return actual responses!
Here’s the wrapper I’m using now:
(updated)
Works for me if I call the handler directly, but not with
mf.dispatchFetch:Works:
It should mock the fetch call for your module code as well. Are you seeing something different?
Wrote a little warpper while we sort out the mock global.
Thanks! That’ll get me back on track, probably using the built-in mocking feature of undici for now.