storage/src/index.test.ts

72 lines
2.4 KiB
TypeScript

import { getLocalStorage, getMemoryStorage, getRemoteStorage } from ".";
import { MemoryStorage, ScopedStorage } from "./basic";
import { BrowserLocalStorage } from "./browser";
import { NodeDirectoryStorage } from "./node";
import { forceNodeStoragesInTempDir } from "./node.test";
import { startTestServer } from "./remote.test";
const localStorage = (window as any).localStorage;
describe(getLocalStorage, () => {
forceNodeStoragesInTempDir();
afterEach(() => {
(window as any).localStorage = localStorage;
});
it("returns the best storage available", async () => {
const mockWarn = jest.spyOn(console, "warn").mockImplementation();
let storage = getLocalStorage("app1");
expect(storage).toBeInstanceOf(ScopedStorage);
expect((storage as any).target).toBeInstanceOf(BrowserLocalStorage);
expect(mockWarn).not.toHaveBeenCalled();
await storage.set("testkey", "testvalue");
expect(await storage.get("testkey")).toBe("testvalue");
storage = getLocalStorage("app1");
expect(await storage.get("testkey")).toBe("testvalue");
storage = getLocalStorage("app2");
expect(await storage.get("testkey")).toBeNull();
delete (window as any)["localStorage"];
storage = getLocalStorage("app1");
expect(storage).toBeInstanceOf(NodeDirectoryStorage);
(NodeDirectoryStorage.findUserData as any).mockImplementation(() => { throw new Error() });
storage = getLocalStorage("app1");
expect(storage).toBeInstanceOf(MemoryStorage);
expect(mockWarn).toHaveBeenCalledWith("No persistent storage available, using in-memory volatile storage");
});
});
describe(getRemoteStorage, () => {
const server = startTestServer();
it("returns a scoped storage", async () => {
let storage = getRemoteStorage("app1", `http://localhost:${server.port()}`);
await storage.set("testkey", "testvalue");
expect(await storage.get("testkey")).toBe("testvalue");
storage = getRemoteStorage("app1", `http://localhost:${server.port()}`);
expect(await storage.get("testkey")).toBe("testvalue");
storage = getRemoteStorage("app2", `http://localhost:${server.port()}`);
expect(await storage.get("testkey")).toBeNull();
});
it("scopes in a private namespace on shared mode", async () => {
});
});
describe(getMemoryStorage, () => {
it("returns a memory storage", () => {
const storage = getMemoryStorage();
expect(storage).toBeInstanceOf(MemoryStorage);
});
});