-
-
Notifications
You must be signed in to change notification settings - Fork 0
π§ͺ Add testing for nexus/frontend/src/lib/api.ts #24
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
Open
Adityavanjre
wants to merge
3
commits into
main
Choose a base branch
from
fix-api-tests-12264907712659456780
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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,12 @@ | ||
| import type { Config } from 'jest'; | ||
|
|
||
| const config: Config = { | ||
| preset: 'ts-jest', | ||
| testEnvironment: 'jsdom', | ||
| moduleNameMapper: { | ||
| '^@/(.*)$': '<rootDir>/src/$1', | ||
| }, | ||
| setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'], | ||
| }; | ||
|
|
||
| export default config; |
This file contains hidden or 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 @@ | ||
| import '@testing-library/jest-dom'; |
This file contains hidden or 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
This file contains hidden or 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,173 @@ | ||
| import axios from "axios"; | ||
| import MockAdapter from "axios-mock-adapter"; | ||
| import { api } from "../api"; | ||
| import { | ||
| ensureNetworkConsent, | ||
| } from "../network-consent"; | ||
|
|
||
| // Mock dependencies | ||
| jest.mock("../network-consent", () => ({ | ||
| ensureNetworkConsent: jest.fn().mockResolvedValue(undefined), | ||
| ensureRecentUserInteraction: jest.fn().mockResolvedValue(undefined), | ||
| isNetworkConsentError: jest.fn().mockReturnValue(false), | ||
| isNetworkInteractionError: jest.fn().mockReturnValue(false), | ||
| })); | ||
|
|
||
| jest.mock("../desktop-offline", () => ({ | ||
| shouldHandleDesktopOfflineRequest: jest.fn().mockReturnValue(false), | ||
| handleDesktopOfflineRequest: jest.fn(), | ||
| })); | ||
|
|
||
| describe("api interceptors and configuration", () => { | ||
| let mockApi: MockAdapter; | ||
| let mockAxios: MockAdapter; | ||
|
|
||
| const originalLocation = window.location; | ||
|
|
||
| beforeEach(() => { | ||
| jest.spyOn(console, 'warn').mockImplementation(() => {}); | ||
| jest.spyOn(console, 'error').mockImplementation(() => {}); | ||
| mockApi = new MockAdapter(api); | ||
| mockAxios = new MockAdapter(axios); // for the refresh token axios.post call | ||
|
|
||
| // Clear mocks | ||
| jest.clearAllMocks(); | ||
|
|
||
| // Reset document.cookie | ||
| Object.defineProperty(document, "cookie", { | ||
| writable: true, | ||
| value: "", | ||
| }); | ||
|
|
||
| // Reset window/localStorage things | ||
| const localStorageMock = { | ||
| getItem: jest.fn(), | ||
| setItem: jest.fn(), | ||
| removeItem: jest.fn(), | ||
| }; | ||
| Object.defineProperty(window, "localStorage", { | ||
| value: localStorageMock, | ||
| writable: true, | ||
| }); | ||
|
|
||
| Object.defineProperty(window, "dispatchEvent", { | ||
| value: jest.fn(), | ||
| writable: true, | ||
| }); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| jest.restoreAllMocks(); | ||
| mockApi.restore(); | ||
| mockAxios.restore(); | ||
| (window as unknown as Record<string, unknown>).location = originalLocation; | ||
| }); | ||
|
|
||
| it("should inject CSRF token on mutating requests", async () => { | ||
| document.cookie = "nexus-csrf=test-csrf-token"; | ||
|
|
||
| mockApi.onPost("/test").reply((config) => { | ||
| return [200, { headers: config.headers }]; | ||
| }); | ||
|
|
||
| const response = await api.post("/test"); | ||
| expect(response.data.headers["X-CSRF-Token"]).toBe("test-csrf-token"); | ||
| }); | ||
|
|
||
| it("should not inject CSRF token on GET requests", async () => { | ||
| document.cookie = "nexus-csrf=test-csrf-token"; | ||
|
|
||
| mockApi.onGet("/test-get").reply((config) => { | ||
| return [200, { headers: config.headers }]; | ||
| }); | ||
|
|
||
| const response = await api.get("/test-get"); | ||
| expect(response.data.headers["X-CSRF-Token"]).toBeUndefined(); | ||
| }); | ||
|
|
||
| it("should trigger soft refresh on x-app-version mismatch", async () => { | ||
| (window.localStorage.getItem as jest.Mock).mockReturnValue("v1"); | ||
|
|
||
| mockApi.onGet("/version-test").reply(200, {}, { "x-app-version": "v2" }); | ||
|
|
||
| await api.get("/version-test"); | ||
|
|
||
| expect(window.localStorage.setItem).toHaveBeenCalledWith("nexus_version", "v2"); | ||
| }); | ||
|
|
||
| it("should not trigger soft refresh if versions match", async () => { | ||
| (window.localStorage.getItem as jest.Mock).mockReturnValue("v1"); | ||
|
|
||
| mockApi.onGet("/version-test").reply(200, {}, { "x-app-version": "v1" }); | ||
|
|
||
| await api.get("/version-test"); | ||
|
|
||
| expect(window.localStorage.setItem).not.toHaveBeenCalledWith("nexus_version", "v1"); | ||
| // expect(window.location.reload).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("should set initial version if not present", async () => { | ||
| (window.localStorage.getItem as jest.Mock).mockReturnValue(null); | ||
|
|
||
| mockApi.onGet("/version-test").reply(200, {}, { "x-app-version": "v1" }); | ||
|
|
||
| await api.get("/version-test"); | ||
|
|
||
| expect(window.localStorage.setItem).toHaveBeenCalledWith("nexus_version", "v1"); | ||
| // expect(window.location.reload).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("should reject with network offline payload when ERR_NETWORK", async () => { | ||
| mockApi.onGet("/offline-test").networkError(); | ||
|
|
||
| await expect(api.get("/offline-test")).rejects.toEqual({ | ||
| message: "Offline Mode: Please check your internet connection.", | ||
| isOffline: true, | ||
| }); | ||
|
|
||
| expect(window.dispatchEvent).toHaveBeenCalledWith(expect.any(CustomEvent)); | ||
| expect((window.dispatchEvent as jest.Mock).mock.calls[0][0].type).toBe("offline-mode"); | ||
| }); | ||
|
|
||
| it("should handle 429 rate limit correctly", async () => { | ||
| mockApi.onGet("/rate-limit").reply(429); | ||
|
|
||
| await expect(api.get("/rate-limit")).rejects.toEqual({ | ||
| message: "Klypso Cloud is waking up. Please try again after 90s.", | ||
| status: 429, | ||
| isRateLimited: true, | ||
| }); | ||
| }); | ||
|
|
||
| it("should handle 503 Server Overload correctly", async () => { | ||
| mockApi.onGet("/wakeup").reply(503); | ||
|
|
||
| await expect(api.get("/wakeup")).rejects.toEqual({ | ||
| message: "Klypso Cloud is waking up. Please wait 90 seconds and try again.", | ||
| isWakeup: true, | ||
| }); | ||
| }); | ||
|
|
||
| it("should dispatch session-expired on 401 when not on auth page", async () => { | ||
| mockApi.onGet("/unauth").reply(401, { code: "OTHER" }); | ||
|
|
||
| await expect(api.get("/unauth")).rejects.toThrow(); | ||
|
|
||
| expect(window.localStorage.removeItem).toHaveBeenCalledWith("k_user"); | ||
| expect(window.dispatchEvent).toHaveBeenCalledWith(expect.any(CustomEvent)); | ||
| expect((window.dispatchEvent as jest.Mock).mock.calls[0][0].type).toBe("session-expired"); | ||
| }); | ||
|
|
||
| it("should attempt token refresh on 401 TOKEN_EXPIRED", async () => { | ||
| mockApi.onGet("/protected").replyOnce(401, { code: "TOKEN_EXPIRED" }); | ||
| mockApi.onGet("/protected").reply(200, { success: true }); | ||
|
|
||
| mockAxios.onPost(/\/auth\/refresh/).reply(200, { user: { id: 1 } }); | ||
|
|
||
| const response = await api.get("/protected"); | ||
|
|
||
| expect(ensureNetworkConsent).toHaveBeenCalled(); | ||
| expect(window.localStorage.setItem).toHaveBeenCalledWith("k_user", JSON.stringify({ id: 1 })); | ||
| expect(response.data.success).toBe(true); | ||
| }); | ||
|
Adityavanjre marked this conversation as resolved.
|
||
| }); | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.