Skip to content

Commit

Permalink
Add unit tests for net helper
Browse files Browse the repository at this point in the history
  • Loading branch information
jpwilliams committed Apr 19, 2024
1 parent b301008 commit fa50dcd
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions packages/inngest/src/helpers/net.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import fetchMock from "jest-fetch-mock";
import { fetchWithAuthFallback } from "./net";

describe("fetchWithAuthFallback", () => {
beforeEach(() => {
fetchMock.resetMocks();
});

it("should make a fetch request with the provided auth token", async () => {
fetchMock.mockResponseOnce(JSON.stringify({ data: "12345" }));

const response = await fetchWithAuthFallback({
authToken: "testToken",
fetch: fetchMock as typeof fetch,
url: "https://example.com",
});

expect(fetchMock).toHaveBeenCalledWith("https://example.com", {
headers: {
Authorization: "Bearer testToken",
},
});
expect(response.status).toEqual(200);
});

it("should retry with the fallback token if the first request fails with 401", async () => {
fetchMock.mockResponses(
[JSON.stringify({}), { status: 401 }],
[JSON.stringify({ data: "12345" }), { status: 200 }]
);

const response = await fetchWithAuthFallback({
authToken: "testToken",
authTokenFallback: "fallbackToken",
fetch: fetchMock as typeof fetch,
url: "https://example.com",
});

expect(fetchMock).toHaveBeenNthCalledWith(1, "https://example.com", {
headers: {
Authorization: "Bearer testToken",
},
});
expect(fetchMock).toHaveBeenNthCalledWith(2, "https://example.com", {
headers: {
Authorization: "Bearer fallbackToken",
},
});
expect(response.status).toEqual(200);
});

it("should not retry with the fallback token if the first request fails with a non-401/403 status", async () => {
fetchMock.mockResponseOnce(JSON.stringify({}), { status: 500 });

const response = await fetchWithAuthFallback({
authToken: "testToken",
authTokenFallback: "fallbackToken",
fetch: fetchMock as typeof fetch,
url: "https://example.com",
});

expect(fetchMock).toHaveBeenCalledTimes(1);
expect(response.status).toEqual(500);
});
});

0 comments on commit fa50dcd

Please sign in to comment.