Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(auth): auth refresh tokens #4499

Merged
merged 2 commits into from
Sep 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 } 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
Loading