import { ensureMuniIssuesCollection, ensureMuniIssuesCollectionOnce, } from "../muniIssues.setup"; import { generateMuniIssueId, getMuniIssuesCollection, } from "../muniIssues.getters"; import { createMuniIssue } from "../muniIssues.setters"; import { getDb } from "../../index"; import { MUNI_ISSUES_COLLECTION } from "../muniIssues.constants"; import { createMuniIssueInput } from "../../../test-utils/factories"; describe("muniIssues setup", () => { describe("ensureMuniIssuesCollection", () => { it("should create the collection with a validator and the declared indexes", async () => { await ensureMuniIssuesCollection(); const [collection] = (await getDb() .listCollections({ name: MUNI_ISSUES_COLLECTION }) .toArray()) as { options?: { validator?: unknown } }[]; expect(collection?.options?.validator).toHaveProperty("$jsonSchema"); const indexNames = (await getMuniIssuesCollection().indexes()).map( (i) => i.name, ); expect(indexNames).toEqual( expect.arrayContaining([ "callSid_1", "createdAt_-1", "jira_key_unique", ]), ); }); it("should accept a valid document and reject ones that violate the schema", async () => { await ensureMuniIssuesCollection(); await expect( createMuniIssue(createMuniIssueInput(), generateMuniIssueId()), ).resolves.toBeDefined(); // Missing required issueContent fields → DB validation rejects it. await expect( getMuniIssuesCollection().insertOne({ callSid: "CA-bad", createdAt: new Date(), } as never), ).rejects.toThrow(); // jira.syncStatus outside the enum → DB validation rejects it. await expect( createMuniIssue( createMuniIssueInput({ jira: { key: "CP-99", syncStatus: "weird" as never }, }), generateMuniIssueId(), ), ).rejects.toThrow(); }); it("should enforce the unique jira.key index", async () => { await ensureMuniIssuesCollection(); const input = createMuniIssueInput(); await createMuniIssue(input, generateMuniIssueId()); // Same jira.key on a second insert violates the unique index. await expect( createMuniIssue(input, generateMuniIssueId()), ).rejects.toThrow(); }); it("should be idempotent when run twice", async () => { await ensureMuniIssuesCollection(); await expect(ensureMuniIssuesCollection()).resolves.toBeUndefined(); }); }); describe("ensureMuniIssuesCollectionOnce", () => { it("should run the provisioning work at most once per process", async () => { const createSpy = jest.spyOn(getDb(), "createCollection"); await Promise.all([ ensureMuniIssuesCollectionOnce(), ensureMuniIssuesCollectionOnce(), ]); await ensureMuniIssuesCollectionOnce(); expect(createSpy).toHaveBeenCalledTimes(1); }); }); });