Skip to content

Commit

Permalink
feat(auth): refresh for relay
Browse files Browse the repository at this point in the history
  • Loading branch information
mikeldking committed Sep 5, 2024
1 parent fe5a1e3 commit f14e50c
Show file tree
Hide file tree
Showing 11 changed files with 583 additions and 46 deletions.
59 changes: 59 additions & 0 deletions app/__tests__/authFetch.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { authFetch, refreshTokens } from "@phoenix/authFetch";
jest.mock("@phoenix/config");

describe("authFetch", () => {
const _fetch = global.fetch;
afterEach(() => {
jest.clearAllMocks();
});

afterEach(() => {
global.fetch = _fetch;
});
it("should call fetch with the provided input and init", async () => {
// @ts-expect-error mock global fetch
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ data: "12345" }),
})
);

const response = await authFetch("/test", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ test: "test" }),
}).then((res) => res.json());

expect(response).toEqual({ data: "12345" });
});
it("should try to refresh the tokens if it gets a 401", async () => {
let count = 0;
// @ts-expect-error mock global fetch
global.fetch = jest.fn(() => {
count += 1;
return Promise.resolve({
status: count === 1 ? 401 : 200,
ok: count === 1 ? false : true,
json: () => Promise.resolve(),
});
});

await authFetch("/test", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ test: "test" }),
});

expect(count).toBe(3);
// @ts-expect-error mock global fetch
expect(global.fetch.mock.calls[0][0]).toBe("/test");
// @ts-expect-error mock global fetch
expect(global.fetch.mock.calls[1][0]).toBe("http://localhost/auth/refresh");
// @ts-expect-error mock global fetch
expect(global.fetch.mock.calls[2][0]).toBe("/test");
});
});
2 changes: 1 addition & 1 deletion app/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// eslint-disable-next-line no-undef
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
testEnvironment: "jsdom",
prettierPath: null,
transform: {
"^.+\\.[jt]sx?$": ["esbuild-jest"],
Expand Down
1 change: 1 addition & 0 deletions app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@
"eslint-plugin-simple-import-sort": "^10.0.0",
"graphql": "^16.9.0",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"only-allow": "^1.2.1",
"prettier": "^3.3.3",
"relay-compiler": "^16.2.0",
Expand Down
Loading

0 comments on commit f14e50c

Please sign in to comment.