diff --git a/src/mock.ts b/src/mock.ts index 1193ec9..ef8bbf9 100644 --- a/src/mock.ts +++ b/src/mock.ts @@ -80,6 +80,8 @@ const MOCKED_FETCH = async (_request: Request | RegExp | string, init?: RequestI if(process.env.VERBOSE) console.debug("\x1b[2mMocked fetch called\x1b[0m", _path); + if (mockedRequest[1].throw) throw mockedRequest[1].throw; + const mockedStatus = mockedRequest[1].response?.status || 200; return makeResponse(mockedStatus, _path, mockedRequest[1]); diff --git a/src/types.ts b/src/types.ts index 43d5b4a..2e59342 100644 --- a/src/types.ts +++ b/src/types.ts @@ -8,6 +8,7 @@ export type MockOptions = { headers?: RequestInit['headers']; method?: RequestInit['method']; response?: MockResponse; + throw?: Error; }; /** diff --git a/tests/mock.test.ts b/tests/mock.test.ts index 3adc3de..1ee62bd 100644 --- a/tests/mock.test.ts +++ b/tests/mock.test.ts @@ -192,6 +192,20 @@ describe("Mock", () => { expect(response.headers).toEqual({ "x-baz-qux": "quux" }); }); + test("mock: should mock a request that throws a fetch error", async () => { + const request = new Request(`${API_URL}/cats`); + const options: MockOptions = { + throw: new Error("Mocked error"), + }; + mock(request, options); + try { + await fetch(`${API_URL}/cats`); + expect().fail(); + } catch (e) { + expect(e.message).toEqual("Mocked error"); + } + }); + test("mock: should not mock a request if it is not registered", async () => { const act = async () => { await fetch(`${API_URL}/posts`);