Rework every test body into // Arrange / // Act / // Assert blocks separated by blank lines: the factory is arranged once, the matcher is built from it in a single act, and all type/runtime checks sink to the end. index.test.ts adopts the same shape. Also migrate off expect-type's deprecated toMatchTypeOf: the checks are assignability tests, so toExtend is the faithful replacement.
72 lines
2.0 KiB
TypeScript
72 lines
2.0 KiB
TypeScript
/* oxlint-disable typescript/no-floating-promises -- expectTypeOf() is a sync type-assertion library that the type-aware linter misidentifies as a promise */
|
|
import { strict as assert } from "node:assert";
|
|
import { test } from "node:test";
|
|
|
|
import { expectTypeOf } from "expect-type";
|
|
|
|
import { type Matcher, P, match } from "./index.ts";
|
|
|
|
test("match returns a builder", () => {
|
|
// Act
|
|
const builder = match("x");
|
|
|
|
// Assert
|
|
expectTypeOf(builder).toHaveProperty("with");
|
|
expectTypeOf(builder).toHaveProperty("exhaustive");
|
|
expectTypeOf(builder).toHaveProperty("otherwise");
|
|
});
|
|
|
|
test("P.literal narrows to its literal type", () => {
|
|
// Act
|
|
const matcher = P.literal("yes");
|
|
|
|
// Assert
|
|
expectTypeOf(matcher).toExtend<Matcher<"yes">>();
|
|
assert.equal(matcher.matches("yes"), true);
|
|
assert.equal(matcher.matches("no"), false);
|
|
});
|
|
|
|
test("P.type narrows to the typeof target", () => {
|
|
// Act
|
|
const matcher = P.type<string>("string");
|
|
|
|
// Assert
|
|
expectTypeOf(matcher).toExtend<Matcher<string>>();
|
|
assert.equal(matcher.matches("hi"), true);
|
|
assert.equal(matcher.matches(42), false);
|
|
});
|
|
|
|
test("exhaustive() returns the union of handler return types", () => {
|
|
// Act
|
|
const result = match<"a" | "b">("a")
|
|
.with(P.literal("a"), () => 1 as const)
|
|
.with(P.literal("b"), () => "two" as const)
|
|
.exhaustive();
|
|
|
|
// Assert
|
|
expectTypeOf(result).toEqualTypeOf<1 | "two">();
|
|
assert.equal(result, 1);
|
|
});
|
|
|
|
test("otherwise() falls back when no case matches", () => {
|
|
// Act
|
|
const result = match<"x" | "y" | "z">("z")
|
|
.with(P.literal("x"), (v): string => `got ${v}`)
|
|
.otherwise((v): string => `fallback ${v}`);
|
|
|
|
// Assert
|
|
assert.equal(result, "fallback z");
|
|
});
|
|
|
|
test("exhaustive throws when no case matches", () => {
|
|
// Assert
|
|
assert.throws(
|
|
() =>
|
|
match<"a" | "b" | "c">("c")
|
|
.with(P.literal("a"), () => "A")
|
|
.with(P.literal("b"), () => "B")
|
|
.exhaustive(),
|
|
/no matching case/,
|
|
);
|
|
});
|