diff --git a/util.ts b/util.ts index 65f26ac..4bd3015 100644 --- a/util.ts +++ b/util.ts @@ -3,13 +3,20 @@ import type { Predicate } from "./is.ts"; export type AssertMessageFactory = ( x: unknown, pred: Predicate, + name?: string, ) => string; -export const defaultAssertMessageFactory: AssertMessageFactory = (x, pred) => { +export const defaultAssertMessageFactory: AssertMessageFactory = ( + x, + pred, + name, +) => { const p = pred.name || "anonymous predicate"; const t = typeof x; const v = JSON.stringify(x, null, 2); - return `Expected a value that satisfies the predicate ${p}, got ${t}: ${v}`; + return `Expected ${ + name ?? "a value" + } that satisfies the predicate ${p}, got ${t}: ${v}`; }; let assertMessageFactory = defaultAssertMessageFactory; @@ -79,11 +86,11 @@ export function setAssertMessageFactory(factory: AssertMessageFactory): void { export function assert( x: unknown, pred: Predicate, - options: { message?: string } = {}, + options: { message?: string; name?: string } = {}, ): asserts x is T { if (!pred(x)) { throw new AssertError( - options.message ?? assertMessageFactory(x, pred), + options.message ?? assertMessageFactory(x, pred, options.name), ); } } @@ -108,7 +115,7 @@ export function assert( export function ensure( x: unknown, pred: Predicate, - options: { message?: string } = {}, + options: { message?: string; name?: string } = {}, ): T { assert(x, pred, options); return x; diff --git a/util_test.ts b/util_test.ts index 51cdae3..4a01133 100644 --- a/util_test.ts +++ b/util_test.ts @@ -34,13 +34,16 @@ Deno.test("assert", async (t) => { ); }); - await t.step("throws an `AssertError` on false predicate", () => { - assertThrows( - () => assert(x, falsePredicate), - AssertError, - `Expected a value that satisfies the predicate falsePredicate, got symbol: undefined`, - ); - }); + await t.step( + "throws an `AssertError` on false predicate with a custom name", + () => { + assertThrows( + () => assert(x, falsePredicate, { name: "hello world" }), + AssertError, + `Expected hello world that satisfies the predicate falsePredicate, got symbol: undefined`, + ); + }, + ); await t.step( "throws an `AssertError` with a custom message on false predicate", @@ -67,6 +70,17 @@ Deno.test("ensure", async (t) => { ); }); + await t.step( + "throws an `AssertError` on false predicate with a custom name", + () => { + assertThrows( + () => ensure(x, falsePredicate, { name: "hello world" }), + AssertError, + `Expected hello world that satisfies the predicate falsePredicate, got symbol: undefined`, + ); + }, + ); + await t.step( "throws an `AssertError` with a custom message on false predicate", () => {