IanVS / vitest-fetch-mock

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

[docs] fetchMock -> fetchMocker #5

Closed Maxim-Mazurok closed 1 year ago

Maxim-Mazurok commented 1 year ago

I was reviewing code at work and I saw this:

beforeEach(() => {
  const fetchMock = createFetchMock(vi);
  fetchMock.enableMocks();
  fetchMock.mockIf(`/bla`);
});

it("Bla", () => {
  bla();
  expect(fetchMock.mock.calls.length).toEqual(1);
});

I was confused, why we have const fetchMock in beforeEach but then reference fetchMock in the test, it should be undefined there, outside of the scope. Turns out it was because fetchMock is also a global variable. Looking at type definitions, I see that createFetchMock is also called createMocker. So I think it'll make more sense to do this:

beforeEach(() => {
  const fetchMocker = createFetchMock(vi);
  fetchMocker.enableMocks();
  fetchMocker.mockIf(`/bla`);
});

it("Bla", () => {
  bla();
  expect(fetchMock.mock.calls.length).toEqual(1);
});

This way there's no clash and it makes more sense - you create fetchMocker, then fetchMocker.enableMocks() will define global fetchMock for you. Hope this makes sense!