diff --git a/src/index.ts b/src/index.ts index d94cb0b..422e5b1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,7 +1,18 @@ import { vi as vitest } from 'vitest'; import type { Mock } from '@vitest/spy'; -// type-definitions +declare global { + // eslint-disable-next-line no-var + var fetchMock: FetchMock; + + // eslint-disable-next-line @typescript-eslint/no-namespace + namespace NodeJS { + interface Global { + fetchMock: FetchMock; + } + } +} + export type FetchMock = Mock & FetchMockObject; class FetchMockObject { @@ -16,6 +27,7 @@ class FetchMockObject { // enable/disable enableMocks(): FetchMock { globalThis.fetch = this.mockedFetch; + globalThis.fetchMock = this.chainingResultProvider(); return this.chainingResultProvider(); } @@ -333,7 +345,7 @@ export default function createFetchMock(vi: typeof vitest): FetchMock { }) as FetchMock; const fetchMock: FetchMock = mockedFetch as FetchMock; - const fetchMockObject = new FetchMockObject(mockedFetch, globalThis.fetch, () => fetchMock); + const fetchMockObject = new FetchMockObject(mockedFetch, originalFetch, () => fetchMock); copyMethods(fetchMockObject, fetchMock); diff --git a/tests/api.test.ts b/tests/api.test.ts index b16a066..d9b34ef 100644 --- a/tests/api.test.ts +++ b/tests/api.test.ts @@ -747,6 +747,16 @@ describe('conditional mocking', () => { }); }); +it('works globally', async () => { + const fm = createFetchMock(vi); + fm.enableMocks(); + + fetchMock.mockResponseOnce('foo'); + expect(await request()).toBe('foo'); + + fm.disableMocks(); +}); + it('enable/disable', async () => { expect(vi.isMockFunction(globalThis.fetch)).toBe(false); const fetch = createFetchMock(vi); diff --git a/types/test.ts b/types/test.ts index 55965f2..d1a5457 100644 --- a/types/test.ts +++ b/types/test.ts @@ -1,7 +1,7 @@ import setupFm, { type MockResponse } from 'vitest-fetch-mock'; import { vi } from 'vitest'; -const fetchMock = setupFm(vi); +const fm = setupFm(vi); fetchMock.mockResponse(JSON.stringify({foo: "bar"})); fetchMock.mockResponse(JSON.stringify({foo: "bar"}), { @@ -108,10 +108,10 @@ function someSyncStringHandler(): string { return JSON.stringify({foo: "bar"}); } -fetchMock.enableMocks(); -fetchMock.disableMocks(); -fetchMock.doMock(); -fetchMock.dontMock(); -fetchMock.doMockOnce(); -fetchMock.dontMockOnce(); -fetchMock.mockOnce(); +fm.enableMocks(); +fm.disableMocks(); +fm.doMock(); +fm.dontMock(); +fm.doMockOnce(); +fm.dontMockOnce(); +fm.mockOnce();