Add an optional title to assertions.

This commit is contained in:
Bauke 2022-12-27 14:26:00 +01:00
parent 40dc13b644
commit 035cac86cc
Signed by: Bauke
GPG Key ID: C1C0F29952BCF558
2 changed files with 12 additions and 4 deletions

View File

@ -1,24 +1,31 @@
export class AssertionError extends Error { export class AssertionError extends Error {
public readonly actual: string; public readonly actual: string;
public readonly expected: string; public readonly expected: string;
public readonly title: string | undefined;
constructor(message: string, actual: any, expected: any) { constructor(message: string, actual: any, expected: any, title?: string) {
super(message); super(message);
this.actual = JSON.stringify(actual); this.actual = JSON.stringify(actual);
this.expected = JSON.stringify(expected); this.expected = JSON.stringify(expected);
this.title = title;
} }
} }
/** Test execution context with assertions. */ /** Test execution context with assertions. */
export class TestContext { export class TestContext {
/** Assert strict equality with `===`. */ /** Assert strict equality with `===`. */
equals<T>(actual: T, expected: T): void { equals<T>(actual: T, expected: T, title?: string): void {
if (actual === expected) { if (actual === expected) {
return; return;
} }
throw new AssertionError("Failed equals assertion", actual, expected); throw new AssertionError(
"Failed equals assertion",
actual,
expected,
title,
);
} }
} }
@ -120,6 +127,7 @@ export class Result implements ResultData {
if (this.error !== undefined) { if (this.error !== undefined) {
message += `\n %c${this.error.message}`; message += `\n %c${this.error.message}`;
message += this.error.title === undefined ? "" : `: ${this.error.title}`;
message += `\n | Actual: ${this.error.actual}`; message += `\n | Actual: ${this.error.actual}`;
message += `\n | Expected: ${this.error.expected}`; message += `\n | Expected: ${this.error.expected}`;
styles.push("color: pink;"); styles.push("color: pink;");

View File

@ -52,6 +52,6 @@ void setup("subtract", async (group) => {
}); });
group.test("subtract(1, 1) = 2", async (test) => { group.test("subtract(1, 1) = 2", async (test) => {
test.equals(await subtract(1, 1), 2); test.equals(await subtract(1, 1), 2, "extra title");
}); });
}); });