Skip to content

Commit

Permalink
✨ Add option to mock error during fetch (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
sadkebab authored Sep 22, 2024
1 parent d2006b1 commit 63b7235
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export type MockOptions = {
headers?: RequestInit['headers'];
method?: RequestInit['method'];
response?: MockResponse;
throw?: Error;
};

/**
Expand Down
14 changes: 14 additions & 0 deletions tests/mock.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`);
Expand Down

0 comments on commit 63b7235

Please sign in to comment.