diff --git a/client/src/composables/simpleKeyStore.test.ts b/client/src/composables/simpleKeyStore.test.ts new file mode 100644 index 000000000000..e642a6cdaf6d --- /dev/null +++ b/client/src/composables/simpleKeyStore.test.ts @@ -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(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(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(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); + }); +});