import { ObjectId } from "mongodb"; import { faker } from "@faker-js/faker"; import { getGroupsCollection, findGroups, createGroup, updateGroup, removeGroup, } from "../groups.getters"; import { createGroup as createGroupDoc } from "../../../test-utils/factories"; describe("db.groups", () => { describe("getGroupsCollection", () => { it('returns the "groups" collection', () => { expect(getGroupsCollection().collectionName).toBe("groups"); }); }); describe("findGroups", () => { it("returns groups matching the provided filter", async () => { const clientId = faker.string.uuid(); const g1 = createGroupDoc({ clientId, name: "Group A" }); const g2 = createGroupDoc({ clientId, name: "Group B" }); const gOther = createGroupDoc({ clientId: faker.string.uuid(), name: "Group C", }); await getGroupsCollection().insertMany([g1, g2, gOther]); const result = await findGroups({ clientId }); const names = result.map((g) => g.name).sort(); expect(result).toHaveLength(2); expect(names).toEqual(["Group A", "Group B"]); }); }); describe("createGroup", () => { it("inserts a group and returns insertedId", async () => { const toInsert = createGroupDoc({ name: "New Group" }); const insertedId = await createGroup(toInsert); expect(insertedId).toBeInstanceOf(ObjectId); const fromDb = await getGroupsCollection().findOne({ _id: insertedId }); expect(fromDb?.name).toBe("New Group"); expect(fromDb?.clientId).toBe(toInsert.clientId); }); }); describe("updateGroup", () => { it("updates the group and sets updatedAt, returning the updated document", async () => { const original = createGroupDoc({ name: "Before", description: "Old desc", }); const { insertedId } = await getGroupsCollection().insertOne(original); const before = await getGroupsCollection().findOne({ _id: insertedId }); // Add a small delay to ensure updatedAt will be different await new Promise((resolve) => setTimeout(resolve, 10)); const res = await updateGroup( { _id: insertedId }, { name: "After", description: "New desc" }, ); expect(res?._id).toEqual(insertedId); expect(res?.name).toBe("After"); expect(res?.description).toBe("New desc"); expect(new Date(res!.updatedAt).getTime()).toBeGreaterThan( new Date(before!.updatedAt).getTime(), ); }); }); describe("removeGroup", () => { it("removes a group by string id", async () => { const { insertedId } = await getGroupsCollection().insertOne(createGroupDoc()); const result = await removeGroup(insertedId.toHexString()); expect(result.deletedCount).toBe(1); const check = await getGroupsCollection().findOne({ _id: insertedId }); expect(check).toBeNull(); }); }); });