IanVS / vitest-fetch-mock

Vitest mock for fetch, forked from jest-fetch-mock
MIT License
59 stars 7 forks source link

Expose a .calls with normalizeRequest #6

Closed stefnotch closed 1 year ago

stefnotch commented 1 year ago

The example showcases a fetch call made using return fetch('https://google.com');, which then gets tested using

expect(fetch.mock.calls[0][0]).toEqual('https://google.com');

This seems rather brittle to me, since the test would fail when one does return fetch(new Request('https://google.com')) instead.

I propose adding a .calls (or some other name like .normalizedCalls or .requests) property that returns normalized requests instead of [string | Request | undefined, RequestInit | undefined][]

IanVS commented 1 year ago

If you're using expect from jest, you can use .toHaveBeenLastCalledWith() (https://jestjs.io/docs/expect#tohavebeenlastcalledwitharg1-arg2-) along with .toHaveBeenCalledTimes() (https://jestjs.io/docs/expect#tohavebeencalledtimesnumber). Maybe there's a similar matcher built into chai/vitest, I'm not sure as I use expect.

stefnotch commented 1 year ago

I guess I haven't clearly explained my issue.

fetch.mock.calls[0] has the type string | Request | undefined.

If I now want to check if a call was a post request, there is no straightforward way of doing so. I'd have to do the whole normalizing myself.

It'd be lovely if this library provided a utility like that. e.g.

const postReqs = fetchMock.requests().filter(v => v.method === "POST");

// where requests does this
function requests(fetchMock: FetchMock) {
    return fetchMock.mock.calls.map((call) =>
      normalizeRequest(call[0], call[1])
    );
  }
IanVS commented 1 year ago

This isn't something I have time to work on myself, but I'll review a PR if you're willing to put one together.

stefnotch commented 1 year ago

@IanVS Done :)