Skip to content

Commit

Permalink
Add unit tests for useITwinFavorites hook
Browse files Browse the repository at this point in the history
  • Loading branch information
arome committed Nov 22, 2024
1 parent f2df04b commit d9e7e02
Showing 1 changed file with 79 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/

import { renderHook } from "@testing-library/react-hooks";

import { useITwinFavorites } from "./useITwinFavorites";

export function mockFetch(data: any, status = 200) {
return jest.fn().mockImplementationOnce(async () =>
Promise.resolve({
status,
ok: true,
json: () => data,
})
);
}

const accessToken = "test-access-token";

describe("useITwinFavorites", () => {
// Clear mocks before each test
beforeEach(() => {
jest.clearAllMocks();
});

test("should initialize with empty Set", () => {
const { result } = renderHook(() => useITwinFavorites(accessToken));
window.fetch = mockFetch({ iTwins: [] });

expect(result.current.iTwinFavorites).toBeInstanceOf(Set);
expect(result.current.iTwinFavorites.size).toBe(0);
});

test("should fetch favorites on mount", async () => {
const mockFavorites = [
{ id: "1", name: "iTwin1" },
{ id: "2", name: "iTwin2" },
];

window.fetch = mockFetch({ iTwins: mockFavorites });
const { result, waitForNextUpdate } = renderHook(() =>
useITwinFavorites(accessToken)
);

await waitForNextUpdate();
expect(result.current.iTwinFavorites.has("1")).toBe(true);
expect(result.current.iTwinFavorites.has("2")).toBe(true);
expect(result.current.iTwinFavorites.size).toBe(2);
});

test("should handle empty response from API", async () => {
window.fetch = mockFetch({ iTwins: [] });

const { result, waitForNextUpdate } = renderHook(() =>
useITwinFavorites(accessToken)
);

await waitForNextUpdate();
expect(result.current.iTwinFavorites.size).toBe(0);
});

test("should add and remove an iTwin from favorites", async () => {
const { result, waitForNextUpdate } = renderHook(() =>
useITwinFavorites(accessToken)
);
const iTwinId = "test-itwin-id";
window.fetch = mockFetch({});

await result.current.addITwinToFavorites(iTwinId);
await waitForNextUpdate();
expect(result.current.iTwinFavorites.has(iTwinId)).toBe(true);

await result.current.removeITwinFromFavorites(iTwinId);
await waitForNextUpdate();
expect(result.current.iTwinFavorites.has(iTwinId)).toBe(false);
});
});

0 comments on commit d9e7e02

Please sign in to comment.