storage/testing.ts
2021-08-16 18:15:01 +02:00

53 lines
1.4 KiB
TypeScript

import { KeyValueStorage, MemoryStorage } from "./basic.ts";
import { startRestServer } from "./server.ts";
import { describe, expect, getAvailablePort, it } from "./deps.testing.ts";
export { describe, expect, it };
/**
* Basic high-level test suite for any kind storage
*/
export async function basicCheck(storage: KeyValueStorage): Promise<void> {
expect(await storage.get("test")).toBe(null);
await storage.set("test", "val");
expect(await storage.get("test")).toBe("val");
expect(await storage.get("notest")).toBe(null);
await storage.set("test", null);
expect(await storage.get("test")).toBe(null);
}
/**
* Temporarily disable localStorage (constructor will throw error),
* for the duration of the callback
*/
export async function disableLocalStorage(
body: () => Promise<void>,
): Promise<void> {
const ns = window as any;
const removed = ns["localStorage"];
delete ns["localStorage"];
try {
await body();
} finally {
ns["localStorage"] = removed;
}
}
/**
* Run a temporary test server, with memory storage
*/
export async function runTestServer(
body: (url: string) => Promise<void>,
): Promise<void> {
const port = await getAvailablePort({ port: { start: 3000, end: 30000 } });
if (!port) {
throw new Error("No port available for test server");
}
const app = await startRestServer(port, new MemoryStorage());
try {
await body(`http://localhost:${port}`);
} finally {
await app.close();
}
}