UNPKG

local-fake-api

Version:

A simple async local mock API without backend.

94 lines (93 loc) 3.48 kB
import { createLocalStorageApi } from "../fakeApi/localStorageApi"; describe("createLocalStorageApi", () => { const api = createLocalStorageApi("test_notes"); beforeAll(() => { const store = {}; global.localStorage = { getItem: (key) => { var _a; return (_a = store[key]) !== null && _a !== void 0 ? _a : null; }, setItem: (key, value) => { store[key] = value; }, removeItem: (key) => { delete store[key]; }, clear: () => { Object.keys(store).forEach((key) => delete store[key]); }, }; }); let note1; let note2; let note3; beforeEach(async () => { await api.deleteAll(); const r1 = await api.create({ title: "First Title", content: "First Content" }); if (!r1.success || !r1.data) throw new Error("Add failed"); note1 = r1.data.id; const r2 = await api.create({ title: "Second Title", content: "Second Content" }); if (!r2.success || !r2.data) throw new Error("Add failed"); note2 = r2.data.id; const r3 = await api.create({ title: "Third Title", content: "Third Content" }); if (!r3.success || !r3.data) throw new Error("Add failed"); note3 = r3.data.id; }); it("lists all added items", async () => { const res = await api.list(); expect(res.success).toBe(true); if (res.success) { expect(res.data).toHaveLength(3); } }); it("lists items with a filter", async () => { var _a; const res = await api.list({ title: "Second Title" }); expect(res.success).toBe(true); if (res.success) { expect(res.data).toHaveLength(1); expect((_a = res.data) === null || _a === void 0 ? void 0 : _a[0].id).toBe(note2); } }); it("fetches items by their ids", async () => { var _a; const res = await api.get(note1); expect(res.success).toBe(true); if (res.success) { expect((_a = res.data) === null || _a === void 0 ? void 0 : _a.title).toBe("First Title"); } }); it("fetches an item by a non-id key (title)", async () => { var _a; const res = await api.get("Second Title", "title"); expect(res.success).toBe(true); if (res.success) { expect((_a = res.data) === null || _a === void 0 ? void 0 : _a.id).toBe(note2); } }); it("returns null when get by non-id key does not match", async () => { const res = await api.get("No Such Title", "title"); expect(res.success).toBe(true); if (res.success) { expect(res.data).toBeNull(); } }); it("updates an existing item", async () => { var _a; const res = await api.update(note2, { title: "Updated Title" }); expect(res.success).toBe(true); if (res.success) { expect((_a = res.data) === null || _a === void 0 ? void 0 : _a.title).toBe("Updated Title"); } }); it("deletes an item by id", async () => { var _a; await api.delete(note1); const res = await api.list(); expect(res.success).toBe(true); if (res.success) { expect((_a = res.data) === null || _a === void 0 ? void 0 : _a.find((n) => n.id === note1)).toBeUndefined(); } }); });