Skip to content

Commit

Permalink
Add tests for simpleKeyStore
Browse files Browse the repository at this point in the history
  • Loading branch information
davelopez committed Dec 7, 2023
1 parent 7cdcfe5 commit fab5cd3
Showing 1 changed file with 83 additions and 0 deletions.
83 changes: 83 additions & 0 deletions client/src/composables/simpleKeyStore.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import flushPromises from "flush-promises";

import { useSimpleKeyStore } from "./simpleKeyStore";

interface ItemData {
id: string;
name: string;
}

const fetchItem = jest.fn();
const shouldFetch = jest.fn();

describe("useSimpleKeyStore", () => {
beforeEach(() => {
fetchItem.mockClear();
shouldFetch.mockClear();
});

it("should fetch the item if it is not already stored", async () => {
const id = "1";
const item = { id: id, name: "Item 1" };
const fetchParams = { id: id };
const apiResponse = { data: item };

fetchItem.mockResolvedValue(apiResponse);

const { storedItems, getItemById, isLoadingItem } = useSimpleKeyStore<ItemData>(fetchItem);

expect(storedItems.value).toEqual({});
expect(isLoadingItem.value(id)).toBeFalsy();

getItemById.value(id);

expect(isLoadingItem.value(id)).toBeTruthy();
await flushPromises();
expect(isLoadingItem.value(id)).toBeFalsy();
expect(storedItems.value[id]).toEqual(item);
expect(fetchItem).toHaveBeenCalledWith(fetchParams);
});

it("should not fetch the item if it is already stored", async () => {
const id = "1";
const item = { id: id, name: "Item 1" };

fetchItem.mockResolvedValue({ data: item });

const { storedItems, getItemById, isLoadingItem } = useSimpleKeyStore<ItemData>(fetchItem);

storedItems.value[id] = item;

expect(isLoadingItem.value(id)).toBeFalsy();

getItemById.value(id);

expect(isLoadingItem.value(id)).toBeFalsy();
expect(storedItems.value[id]).toEqual(item);
expect(fetchItem).not.toHaveBeenCalled();
});

it("should fetch the item regardless of whether it is already stored if shouldFetch returns true", async () => {
const id = "1";
const item = { id: id, name: "Item 1" };
const fetchParams = { id: id };
const apiResponse = { data: item };

fetchItem.mockResolvedValue(apiResponse);
shouldFetch.mockReturnValue(true);

const { storedItems, getItemById, isLoadingItem } = useSimpleKeyStore<ItemData>(fetchItem, shouldFetch);

storedItems.value[id] = item;

expect(isLoadingItem.value(id)).toBeFalsy();

getItemById.value(id);

expect(isLoadingItem.value(id)).toBeTruthy();
await flushPromises();
expect(isLoadingItem.value(id)).toBeFalsy();
expect(storedItems.value[id]).toEqual(item);
expect(fetchItem).toHaveBeenCalledWith(fetchParams);
});
});

0 comments on commit fab5cd3

Please sign in to comment.