added unique constraint assertion tools

This commit is contained in:
2024-04-09 08:56:28 -05:00
parent 2b2ff8e4ab
commit 1b47be09de
4 changed files with 90 additions and 3 deletions

50
tests/unique.test.ts Normal file
View File

@@ -0,0 +1,50 @@
import { describe, it, expect } from 'vitest';
import { z } from 'zod';
import { assertUniqueKeys } from "../pkg/unique";
describe("assert unique", () => {
it("should assert unique keys in a homogenous array", () => {
const data = [
{ id: 1, name: "John" },
{ id: 2, name: "Doe" },
{ id: 3, name: "Jane" },
];
const validator = z.object({
id: z.number(),
name: z.string(),
});
expect(
() => assertUniqueKeys(data, validator, "id")
).not.toThrow();
})
it("should reject arrays violating unique key constraints", () => {
const data = [
{ id: 1, name: "John" },
{ id: 1, name: "Doe" },
{ id: 1, name: "Jane" },
];
const validator = z.object({
id: z.number(),
name: z.string(),
});
expect(
() => assertUniqueKeys(data, validator, "id")
).toThrowError("Encountered duplicate values in unique field");
})
it("should only allow record types", () => {
const data = [
2, 3, 4, 5, "foo", "bar", true
];
const validator = z.union([z.number(), z.string(), z.boolean()]);
expect(
// @ts-expect-error
() => assertUniqueKeys(data, validator)
).toThrow();
})
})