How to spy on mocked fetch interceptor?

Given the following mock (which is amazing by the way):
// Disable Fetch API from making real network requests
// @see https://undici.nodejs.org/#/docs/api/MockAgent?id=mockagentdisablenetconnect
const fetchMock = getMiniflareFetchMock();
fetchMock.disableNetConnect();

// Intercept calls to Discord's webhook API
const origin = fetchMock.get('https://discord.com');
origin.intercept({ method: 'POST', path: /api\/webhooks\/.*/ }).reply(200, 'Mocked response!');
// Disable Fetch API from making real network requests
// @see https://undici.nodejs.org/#/docs/api/MockAgent?id=mockagentdisablenetconnect
const fetchMock = getMiniflareFetchMock();
fetchMock.disableNetConnect();

// Intercept calls to Discord's webhook API
const origin = fetchMock.get('https://discord.com');
origin.intercept({ method: 'POST', path: /api\/webhooks\/.*/ }).reply(200, 'Mocked response!');
How do I spy on it and then check how often it's called?
expect(spy).toHaveBeenCalledTimes(1)
expect(spy).toHaveBeenCalledTimes(1)
1 Reply
Webber
Webber•2y ago
I've also tried to look through the interceptors API, and this seems to be the closest thing to a spy that I could find, but it doesn't work that way.
const interceptors = fetchMock.pendingInterceptors()[0];

... make a call ...

console.log(interceptors.consumed); // false
console.log(interceptors.timesInvoked); // 0
const interceptors = fetchMock.pendingInterceptors()[0];

... make a call ...

console.log(interceptors.consumed); // false
console.log(interceptors.timesInvoked); // 0
Ah it's actually not that hard once you know it 🙂
const fetchSpy = vi.spyOn(global, 'fetch');

... make a call ...

expect(fetchSpy).toHaveBeenCalledTimes(1);
fetchMock.assertNoPendingInterceptors();
const fetchSpy = vi.spyOn(global, 'fetch');

... make a call ...

expect(fetchSpy).toHaveBeenCalledTimes(1);
fetchMock.assertNoPendingInterceptors();
Mocks + spy combinations are always tricky and really hard to find great examples for most of the time.
Want results from more Discord servers?
Add your server