Skip to content

Commit

Permalink
test(apolloClient): add test for setting authorization header when to…
Browse files Browse the repository at this point in the history
…ken is present in localStorage
  • Loading branch information
amalv committed Jan 15, 2024
1 parent 4209b0d commit 2a29536
Showing 1 changed file with 45 additions and 10 deletions.
55 changes: 45 additions & 10 deletions src/apolloClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,30 @@ import { describe, it, vi } from "vitest";
import { darkModeVar } from "./apolloClient";

describe("apolloClient", () => {
it("creates ApolloClient with correct configuration", () => {
const mocks = vi.hoisted(() => {
const mockLink = {
concat: vi.fn(),
split: vi.fn(),
request: vi.fn(),
setOnError: vi.fn(),
};
return { mockLink };
});
const mocks = vi.hoisted(() => {
const mockLink = {
concat: vi.fn(),
split: vi.fn(),
request: vi.fn(),
setOnError: vi.fn(),
};

const setContextMock = vi
.fn()
.mockImplementation((_, { headers } = { headers: {} }) => {
const token = "test-token";
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
},
concat: vi.fn(),
};
});

return { mockLink, setContextMock };
});
it("creates ApolloClient with correct configuration", () => {
vi.mock("@apollo/client", () => ({
ApolloClient: vi.fn(),
createHttpLink: vi.fn().mockReturnValue(mocks.mockLink),
Expand Down Expand Up @@ -56,4 +69,26 @@ describe("apolloClient", () => {
.typePolicies.Query.fields.darkMode.read;
expect(darkModeReadFunction()).toBe(darkModeVar());
});

it("sets authorization header when token is present in localStorage", () => {
const token = "test-token";
vi.stubGlobal("localStorage", {
getItem: vi.fn().mockReturnValue(token),
});

vi.mock("@apollo/client/link/context", () => ({
setContext: mocks.setContextMock,
}));

const context = mocks.setContextMock({}, { headers: {} });

expect(context).toEqual({
headers: {
authorization: `Bearer ${token}`,
},
concat: expect.any(Function),
});

vi.unstubAllGlobals();
});
});

1 comment on commit 2a29536

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.