-
Notifications
You must be signed in to change notification settings - Fork 37
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
b301008
commit fa50dcd
Showing
1 changed file
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}); | ||
}); |