import { createKyselyMock } from "@tailor-platform/sdk/vitest"; import { expect } from "vitest"; import type { Command } from "../shared/defineCommand"; import { InsufficientPermissionError } from "../shared/errors"; import type { Result, ErrorOf, ValueOf } from "../shared/result"; import type { CommandContext } from "../shared/types"; export function testNotFound>( command: Command, input: TInput, expectedError: abstract new (...args: never[]) => ErrorOf, ) { return async () => { const mock = createKyselyMock(); const ctx: CommandContext = { actorId: "test-actor", permissions: [] }; const result = await mock.withTx((trx) => command(trx, input, ctx)); expect(result.ok).toBe(false); if (!result.ok) { expect(result.error).toBeInstanceOf(expectedError); } }; } export function testPermissionDenied>( command: Command, input: TInput, ) { return async () => { const mock = createKyselyMock(); const denied: CommandContext = { actorId: "test-actor", permissions: [] }; const result = await mock.withTx((trx) => command(trx, input, denied)); expect(result.ok).toBe(false); if (!result.ok) { expect(result.error).toBeInstanceOf(InsufficientPermissionError); } }; } export function testIdempotent< TInput, TReturn extends Result, Error>, TKey extends string & keyof ValueOf, >( command: Command, input: TInput, existingEntity: Record, entityKey: TKey, ) { return async () => { const mock = createKyselyMock(); mock.setQueryResolver((query) => (query.kind === "SelectQueryNode" ? [existingEntity] : [])); const ctx: CommandContext = { actorId: "test-actor", permissions: [] }; const result = await mock.withTx((trx) => command(trx, input, ctx)); expect(result.ok).toBe(true); if (result.ok) { expect(result.value[entityKey]).toEqual(existingEntity); } expect(mock.updates).toHaveLength(0); }; }