@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 763 lines 26.4 KB
Raw
1 /**
2 * A from-scratch, dependency-free `expect` covering the matcher surface used
3 * by the alchemy test suite. Vitest-compatible semantics for:
4 *
5 * - equality: toBe, toEqual, toStrictEqual
6 * - presence: toBeDefined, toBeUndefined, toBeNull, toBeTruthy, toBeFalsy, toBeNaN
7 * - containers: toContain, toContainEqual, toHaveLength, toHaveProperty
8 * - strings: toMatch
9 * - objects: toMatchObject, toBeInstanceOf, toBeTypeOf
10 * - numbers: toBeGreaterThan(OrEqual), toBeLessThan(OrEqual), toBeCloseTo
11 * - misc: toSatisfy, toBeOneOf, toThrow / toThrowError
12 * - modifiers: .not, .resolves, .rejects
13 * - asymmetric: expect.any, expect.anything, expect.arrayContaining,
14 * expect.objectContaining, expect.stringContaining, expect.stringMatching
15 * - expect.fail
16 *
17 * Assertion failures throw {@link AssertionError} (a plain Error subclass) so
18 * they propagate through Effect as defects and render with a clean message.
19 */
20
21 // ---------------------------------------------------------------------------
22 // AssertionError
23 // ---------------------------------------------------------------------------
24
25 export class AssertionError extends Error {
26 override readonly name = "AssertionError";
27 constructor(
28 message: string,
29 readonly actual?: unknown,
30 readonly expected?: unknown,
31 ) {
32 super(message);
33 }
34 }
35
36 // ---------------------------------------------------------------------------
37 // stringify — small, cycle-safe inspector for failure messages
38 // ---------------------------------------------------------------------------
39
40 const MAX_DEPTH = 4;
41 const MAX_ITEMS = 25;
42 const MAX_STRING = 2000;
43
44 export const stringify = (value: unknown): string => {
45 try {
46 const out = inspect(value, 0, new Set());
47 return out.length > MAX_STRING ? `${out.slice(0, MAX_STRING)}…` : out;
48 } catch {
49 // Coercion-hostile values (e.g. alchemy Output proxies throw on string
50 // coercion) must never break assertion-message rendering.
51 return "[unprintable]";
52 }
53 };
54
55 const inspect = (value: unknown, depth: number, seen: Set<unknown>): string => {
56 try {
57 return inspectUnsafe(value, depth, seen);
58 } catch {
59 return "[unprintable]";
60 }
61 };
62
63 const inspectUnsafe = (value: unknown, depth: number, seen: Set<unknown>): string => {
64 if (value === null) return "null";
65 if (value === undefined) return "undefined";
66 switch (typeof value) {
67 case "string":
68 return JSON.stringify(value);
69 case "number":
70 case "boolean":
71 return String(value);
72 case "bigint":
73 return `${value}n`;
74 case "symbol":
75 return value.toString();
76 case "function":
77 return `[Function ${value.name || "anonymous"}]`;
78 }
79 if (isAsymmetric(value)) return value.toString();
80 if (value instanceof Date) return `Date(${value.toISOString()})`;
81 if (value instanceof RegExp) return value.toString();
82 if (value instanceof Error) return `${value.name}(${JSON.stringify(value.message)})`;
83 if (seen.has(value)) return "[Circular]";
84 if (depth > MAX_DEPTH) return Array.isArray(value) ? "[…]" : "{…}";
85 seen.add(value);
86 try {
87 if (Array.isArray(value)) {
88 const items = value.slice(0, MAX_ITEMS).map((v) => inspect(v, depth + 1, seen));
89 if (value.length > MAX_ITEMS) items.push(`… ${value.length - MAX_ITEMS} more`);
90 return `[ ${items.join(", ")} ]`;
91 }
92 if (value instanceof Map) {
93 const items = [...value.entries()]
94 .slice(0, MAX_ITEMS)
95 .map(([k, v]) => `${inspect(k, depth + 1, seen)} => ${inspect(v, depth + 1, seen)}`);
96 return `Map { ${items.join(", ")} }`;
97 }
98 if (value instanceof Set) {
99 const items = [...value.values()].slice(0, MAX_ITEMS).map((v) => inspect(v, depth + 1, seen));
100 return `Set { ${items.join(", ")} }`;
101 }
102 const proto = Object.getPrototypeOf(value);
103 const ctor =
104 proto !== null && proto !== Object.prototype && proto.constructor?.name !== "Object"
105 ? `${proto.constructor?.name ?? ""} `
106 : "";
107 const entries = Object.entries(value as Record<string, unknown>).slice(0, MAX_ITEMS);
108 const body = entries.map(([k, v]) => `${k}: ${inspect(v, depth + 1, seen)}`).join(", ");
109 return `${ctor}{ ${body} }`;
110 } finally {
111 seen.delete(value);
112 }
113 };
114
115 // ---------------------------------------------------------------------------
116 // Asymmetric matchers
117 // ---------------------------------------------------------------------------
118
119 interface AsymmetricMatcher {
120 matches(actual: unknown): boolean;
121 toString(): string;
122 }
123
124 /**
125 * Identity-based registry. A `Symbol in value` check would be unreliable:
126 * alchemy's `Output`/`PropExpr` proxies answer `true` for arbitrary `has`
127 * probes, which would misclassify them as matchers.
128 */
129 const asymmetricRegistry = new WeakSet<object>();
130
131 const isAsymmetric = (value: unknown): value is AsymmetricMatcher =>
132 typeof value === "object" && value !== null && asymmetricRegistry.has(value);
133
134 const asymmetric = (label: string, matches: (actual: unknown) => boolean): AsymmetricMatcher => {
135 const matcher: AsymmetricMatcher = {
136 matches,
137 toString: () => label,
138 };
139 asymmetricRegistry.add(matcher);
140 return matcher;
141 };
142
143 const anyMatcher = (ctor: any): AsymmetricMatcher =>
144 asymmetric(`Any<${ctor?.name ?? "?"}>`, (actual) => {
145 if (ctor === String) return typeof actual === "string" || actual instanceof String;
146 if (ctor === Number) return typeof actual === "number" || actual instanceof Number;
147 if (ctor === Boolean) return typeof actual === "boolean" || actual instanceof Boolean;
148 if (ctor === BigInt) return typeof actual === "bigint";
149 if (ctor === Symbol) return typeof actual === "symbol";
150 if (ctor === Function) return typeof actual === "function";
151 if (ctor === Object) return typeof actual === "object" && actual !== null;
152 if (ctor === Array) return Array.isArray(actual);
153 return actual instanceof ctor;
154 });
155
156 // ---------------------------------------------------------------------------
157 // Deep equality (jest `toEqual` semantics: undefined-valued keys are ignored,
158 // asymmetric matchers are honored on the expected side)
159 // ---------------------------------------------------------------------------
160
161 export const equals = (actual: unknown, expected: unknown, strict = false): boolean =>
162 eq(actual, expected, strict, new Map());
163
164 const definedKeys = (obj: Record<PropertyKey, unknown>): Array<PropertyKey> =>
165 (Reflect.ownKeys(obj) as Array<PropertyKey>).filter((k) => obj[k as any] !== undefined);
166
167 const eq = (a: unknown, b: unknown, strict: boolean, seen: Map<unknown, unknown>): boolean => {
168 if (isAsymmetric(b)) return b.matches(a);
169 if (isAsymmetric(a)) return a.matches(b);
170 if (Object.is(a, b)) return true;
171 if (typeof a !== typeof b) return false;
172 if (typeof a !== "object" || a === null || b === null) return false;
173 const objA = a as Record<PropertyKey, unknown>;
174 const objB = b as Record<PropertyKey, unknown>;
175
176 if (seen.get(a) === b) return true;
177 seen.set(a, b);
178 try {
179 if (a instanceof Date || b instanceof Date) {
180 return a instanceof Date && b instanceof Date && a.getTime() === b.getTime();
181 }
182 if (a instanceof Error || b instanceof Error) {
183 // Vitest semantics: errors match on class, message and own enumerable
184 // fields (e.g. Data.TaggedError payloads) — never on `stack`.
185 if (!(a instanceof Error) || !(b instanceof Error)) return false;
186 if (a.name !== b.name || a.message !== b.message) return false;
187 const fieldsOf = (error: Error): Record<string, unknown> => {
188 const fields: Record<string, unknown> = {};
189 for (const [key, value] of Object.entries(error)) {
190 if (key === "stack" || key === "message" || key === "name") continue;
191 if (value !== undefined) fields[key] = value;
192 }
193 return fields;
194 };
195 return eq(fieldsOf(a), fieldsOf(b), false, seen);
196 }
197 if (a instanceof RegExp || b instanceof RegExp) {
198 return (
199 a instanceof RegExp && b instanceof RegExp && a.source === b.source && a.flags === b.flags
200 );
201 }
202 if (a instanceof URL || b instanceof URL) {
203 return a instanceof URL && b instanceof URL && a.href === b.href;
204 }
205 if (Array.isArray(a) || Array.isArray(b)) {
206 if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) {
207 return false;
208 }
209 for (let i = 0; i < a.length; i++) {
210 if (!eq(a[i], b[i], strict, seen)) return false;
211 }
212 return true;
213 }
214 if (a instanceof Map || b instanceof Map) {
215 if (!(a instanceof Map) || !(b instanceof Map) || a.size !== b.size) {
216 return false;
217 }
218 for (const [k, v] of a) {
219 if (!b.has(k) || !eq(v, b.get(k), strict, seen)) return false;
220 }
221 return true;
222 }
223 if (a instanceof Set || b instanceof Set) {
224 if (!(a instanceof Set) || !(b instanceof Set) || a.size !== b.size) {
225 return false;
226 }
227 outer: for (const v of a) {
228 if (b.has(v)) continue;
229 for (const w of b) {
230 if (eq(v, w, strict, seen)) continue outer;
231 }
232 return false;
233 }
234 return true;
235 }
236 if (ArrayBuffer.isView(a) || ArrayBuffer.isView(b)) {
237 if (!ArrayBuffer.isView(a) || !ArrayBuffer.isView(b)) return false;
238 const ta = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
239 const tb = new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
240 if (ta.length !== tb.length) return false;
241 for (let i = 0; i < ta.length; i++) if (ta[i] !== tb[i]) return false;
242 return true;
243 }
244 if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) {
245 return false;
246 }
247 const keysA = strict ? Reflect.ownKeys(objA) : definedKeys(objA);
248 const keysB = strict ? Reflect.ownKeys(objB) : definedKeys(objB);
249 if (keysA.length !== keysB.length) return false;
250 for (const k of keysA) {
251 if (!(k in objB) && objB[k as any] === undefined && !strict) return false;
252 if (!eq(objA[k as any], objB[k as any], strict, seen)) return false;
253 }
254 return true;
255 } finally {
256 seen.delete(a);
257 }
258 };
259
260 /**
261 * Object-like values for structural matching. Includes functions because
262 * alchemy's `Output` proxies wrap a function target (so they're callable)
263 * while still exposing data properties.
264 */
265 const isObjectLike = (value: unknown): value is Record<PropertyKey, unknown> =>
266 value !== null && (typeof value === "object" || typeof value === "function");
267
268 /** Subset match for toMatchObject: every key in `expected` must match. */
269 const matchesObject = (
270 actual: unknown,
271 expected: unknown,
272 seen: Map<unknown, unknown>,
273 ): boolean => {
274 if (isAsymmetric(expected)) return expected.matches(actual);
275 if (typeof expected !== "object" || expected === null) {
276 return eq(actual, expected, false, seen);
277 }
278 if (!isObjectLike(actual)) return false;
279 if (Array.isArray(expected)) {
280 if (!Array.isArray(actual) || actual.length !== expected.length) return false;
281 return expected.every((e, i) => matchesObject(actual[i], e, seen));
282 }
283 if (
284 expected instanceof Date ||
285 expected instanceof RegExp ||
286 expected instanceof Map ||
287 expected instanceof Set
288 ) {
289 return eq(actual, expected, false, seen);
290 }
291 if (seen.get(actual) === expected) return true;
292 seen.set(actual, expected);
293 try {
294 for (const k of Reflect.ownKeys(expected as Record<PropertyKey, unknown>)) {
295 const e = (expected as any)[k];
296 if (e === undefined && !(k in (actual as any))) continue;
297 if (!matchesObject((actual as any)[k], e, seen)) return false;
298 }
299 return true;
300 } finally {
301 seen.delete(actual);
302 }
303 };
304
305 // ---------------------------------------------------------------------------
306 // Matchers
307 // ---------------------------------------------------------------------------
308
309 export interface Matchers<A = unknown> {
310 toBe(expected: unknown): void;
311 toEqual(expected: unknown): void;
312 toStrictEqual(expected: unknown): void;
313 toBeDefined(): void;
314 toBeUndefined(): void;
315 toBeNull(): void;
316 toBeTruthy(): void;
317 toBeFalsy(): void;
318 toBeNaN(): void;
319 toContain(item: unknown): void;
320 toContainEqual(item: unknown): void;
321 toHaveLength(length: number): void;
322 toHaveProperty(path: string | Array<PropertyKey>, value?: unknown): void;
323 toMatch(pattern: string | RegExp): void;
324 toMatchObject(expected: object): void;
325 toThrow(expected?: string | RegExp | Error | (new (...args: Array<any>) => Error)): void;
326 toThrowError(expected?: string | RegExp | Error | (new (...args: Array<any>) => Error)): void;
327 toBeGreaterThan(expected: number | bigint): void;
328 toBeGreaterThanOrEqual(expected: number | bigint): void;
329 toBeLessThan(expected: number | bigint): void;
330 toBeLessThanOrEqual(expected: number | bigint): void;
331 toBeCloseTo(expected: number, precision?: number): void;
332 toBeInstanceOf(ctor: abstract new (...args: Array<any>) => unknown): void;
333 toBeTypeOf(
334 type:
335 | "string"
336 | "number"
337 | "boolean"
338 | "bigint"
339 | "symbol"
340 | "function"
341 | "object"
342 | "undefined",
343 ): void;
344 toSatisfy(predicate: (value: A) => boolean): void;
345 toBeOneOf(values: ReadonlyArray<unknown>): void;
346 readonly not: Matchers<A>;
347 readonly resolves: PromiseMatchers<A>;
348 readonly rejects: PromiseMatchers<A>;
349 }
350
351 export type PromiseMatchers<A> = {
352 readonly [K in Exclude<keyof Matchers<A>, "not" | "resolves" | "rejects">]: (
353 ...args: Parameters<Matchers<A>[K]>
354 ) => Promise<void>;
355 } & { readonly not: PromiseMatchers<A> };
356
357 const fail = (message: string, actual?: unknown, expected?: unknown): never => {
358 throw new AssertionError(message, actual, expected);
359 };
360
361 const check = (
362 pass: boolean,
363 negated: boolean,
364 message: () => string,
365 actual?: unknown,
366 expected?: unknown,
367 ): void => {
368 if (pass === negated) {
369 fail(negated ? `NOT: ${message()}` : message(), actual, expected);
370 }
371 };
372
373 const resolveThrown = (actual: unknown): { threw: boolean; error: unknown } => {
374 if (typeof actual !== "function") {
375 // expect(error).toThrow — vitest allows passing an already-caught error
376 return { threw: true, error: actual };
377 }
378 try {
379 (actual as () => unknown)();
380 return { threw: false, error: undefined };
381 } catch (error) {
382 return { threw: true, error };
383 }
384 };
385
386 const throwMatches = (
387 error: unknown,
388 expected?: string | RegExp | Error | (new (...args: Array<any>) => Error),
389 ): boolean => {
390 if (expected === undefined) return true;
391 const message = error instanceof Error ? error.message : String(error);
392 if (typeof expected === "string") return message.includes(expected);
393 if (expected instanceof RegExp) return expected.test(message);
394 if (expected instanceof Error) return message === expected.message;
395 return error instanceof expected;
396 };
397
398 const getPath = (
399 target: unknown,
400 path: string | Array<PropertyKey>,
401 ): { found: boolean; value: unknown } => {
402 const parts = Array.isArray(path)
403 ? path
404 : path.split(".").flatMap((segment) =>
405 segment
406 .split(/[[\]]/)
407 .filter((s) => s !== "")
408 .map((s) => (/^\d+$/.test(s) ? Number(s) : s)),
409 );
410 let current: any = target;
411 for (const part of parts) {
412 if (current === null || current === undefined || !(part in Object(current))) {
413 return { found: false, value: undefined };
414 }
415 current = current[part as any];
416 }
417 return { found: true, value: current };
418 };
419
420 const makeMatchers = <A>(actual: A, negated: boolean): Matchers<A> => {
421 const str = (v: unknown) => stringify(v);
422 const self: Matchers<A> = {
423 toBe: (expected) =>
424 check(
425 Object.is(actual, expected),
426 negated,
427 () => `expected ${str(actual)} to be ${str(expected)}`,
428 actual,
429 expected,
430 ),
431 toEqual: (expected) =>
432 check(
433 equals(actual, expected),
434 negated,
435 () => `expected ${str(actual)} to equal ${str(expected)}`,
436 actual,
437 expected,
438 ),
439 toStrictEqual: (expected) =>
440 check(
441 equals(actual, expected, true),
442 negated,
443 () => `expected ${str(actual)} to strictly equal ${str(expected)}`,
444 actual,
445 expected,
446 ),
447 toBeDefined: () => check(actual !== undefined, negated, () => `expected value to be defined`),
448 toBeUndefined: () =>
449 check(actual === undefined, negated, () => `expected ${str(actual)} to be undefined`),
450 toBeNull: () => check(actual === null, negated, () => `expected ${str(actual)} to be null`),
451 toBeTruthy: () => check(!!actual, negated, () => `expected ${str(actual)} to be truthy`),
452 toBeFalsy: () => check(!actual, negated, () => `expected ${str(actual)} to be falsy`),
453 toBeNaN: () =>
454 check(
455 typeof actual === "number" && Number.isNaN(actual),
456 negated,
457 () => `expected ${str(actual)} to be NaN`,
458 ),
459 toContain: (item) => {
460 let pass = false;
461 if (typeof actual === "string") {
462 pass = typeof item === "string" && actual.includes(item);
463 } else if (Array.isArray(actual)) {
464 pass = actual.includes(item);
465 } else if (actual instanceof Set) {
466 pass = actual.has(item);
467 } else if (
468 actual !== null &&
469 typeof actual === "object" &&
470 Symbol.iterator in (actual as object)
471 ) {
472 pass = [...(actual as unknown as Iterable<unknown>)].includes(item);
473 }
474 check(pass, negated, () => `expected ${str(actual)} to contain ${str(item)}`, actual, item);
475 },
476 toContainEqual: (item) => {
477 const values = Array.isArray(actual)
478 ? actual
479 : actual instanceof Set
480 ? [...actual]
481 : actual !== null && typeof actual === "object" && Symbol.iterator in (actual as object)
482 ? [...(actual as unknown as Iterable<unknown>)]
483 : undefined;
484 check(
485 values !== undefined && values.some((v) => equals(v, item)),
486 negated,
487 () => `expected ${str(actual)} to contain an element equal to ${str(item)}`,
488 actual,
489 item,
490 );
491 },
492 toHaveLength: (length) => {
493 const actualLength =
494 typeof actual === "string" || Array.isArray(actual)
495 ? actual.length
496 : ((actual as any)?.length ?? (actual as any)?.size);
497 check(
498 actualLength === length,
499 negated,
500 () => `expected length ${str(actualLength)} to be ${length} (value: ${str(actual)})`,
501 actualLength,
502 length,
503 );
504 },
505 toHaveProperty: (path, ...rest) => {
506 const { found, value } = getPath(actual, path);
507 const pass = found && (rest.length === 0 || equals(value, rest[0]));
508 check(
509 pass,
510 negated,
511 () =>
512 rest.length === 0
513 ? `expected ${str(actual)} to have property ${JSON.stringify(String(path))}`
514 : `expected property ${JSON.stringify(String(path))} of ${str(actual)} to equal ${str(rest[0])}, got ${str(value)}`,
515 value,
516 rest[0],
517 );
518 },
519 toMatch: (pattern) => {
520 const text = typeof actual === "string" ? actual : undefined;
521 const pass =
522 text !== undefined &&
523 (typeof pattern === "string" ? text.includes(pattern) : pattern.test(text));
524 check(
525 pass,
526 negated,
527 () => `expected ${str(actual)} to match ${str(pattern)}`,
528 actual,
529 pattern,
530 );
531 },
532 toMatchObject: (expected) =>
533 check(
534 matchesObject(actual, expected, new Map()),
535 negated,
536 () => `expected ${str(actual)} to match object ${str(expected)}`,
537 actual,
538 expected,
539 ),
540 toThrow: (expected) => {
541 const { threw, error } = resolveThrown(actual);
542 check(
543 threw && throwMatches(error, expected),
544 negated,
545 () =>
546 threw
547 ? `expected thrown error ${str(error)} to match ${str(expected)}`
548 : `expected function to throw`,
549 error,
550 expected,
551 );
552 },
553 toThrowError: (expected) => self.toThrow(expected),
554 toBeGreaterThan: (expected) =>
555 check(
556 (actual as any) > expected,
557 negated,
558 () => `expected ${str(actual)} to be greater than ${str(expected)}`,
559 actual,
560 expected,
561 ),
562 toBeGreaterThanOrEqual: (expected) =>
563 check(
564 (actual as any) >= expected,
565 negated,
566 () => `expected ${str(actual)} to be >= ${str(expected)}`,
567 actual,
568 expected,
569 ),
570 toBeLessThan: (expected) =>
571 check(
572 (actual as any) < expected,
573 negated,
574 () => `expected ${str(actual)} to be less than ${str(expected)}`,
575 actual,
576 expected,
577 ),
578 toBeLessThanOrEqual: (expected) =>
579 check(
580 (actual as any) <= expected,
581 negated,
582 () => `expected ${str(actual)} to be <= ${str(expected)}`,
583 actual,
584 expected,
585 ),
586 toBeCloseTo: (expected, precision = 2) =>
587 check(
588 typeof actual === "number" && Math.abs(actual - expected) < 10 ** -precision / 2,
589 negated,
590 () => `expected ${str(actual)} to be close to ${expected} (precision ${precision})`,
591 actual,
592 expected,
593 ),
594 toBeInstanceOf: (ctor) =>
595 check(
596 actual instanceof ctor,
597 negated,
598 () => `expected ${str(actual)} to be an instance of ${ctor.name}`,
599 actual,
600 ctor,
601 ),
602 toBeTypeOf: (type) =>
603 check(
604 typeof actual === type,
605 negated,
606 () => `expected ${str(actual)} (${typeof actual}) to be of type ${type}`,
607 typeof actual,
608 type,
609 ),
610 toSatisfy: (predicate) =>
611 check(
612 predicate(actual),
613 negated,
614 () => `expected ${str(actual)} to satisfy ${predicate.name || "predicate"}`,
615 actual,
616 ),
617 toBeOneOf: (values) =>
618 check(
619 values.some((v) => equals(actual, v)),
620 negated,
621 () => `expected ${str(actual)} to be one of ${str(values)}`,
622 actual,
623 values,
624 ),
625 get not() {
626 return makeMatchers(actual, !negated);
627 },
628 get resolves() {
629 return makePromiseMatchers(actual, negated, "resolves");
630 },
631 get rejects() {
632 return makePromiseMatchers(actual, negated, "rejects");
633 },
634 };
635 return self;
636 };
637
638 const makePromiseMatchers = <A>(
639 actual: A,
640 negated: boolean,
641 kind: "resolves" | "rejects",
642 ): PromiseMatchers<A> => {
643 const settle = async (): Promise<unknown> => {
644 const promise = typeof actual === "function" ? (actual as any)() : actual;
645 if (kind === "resolves") return await promise;
646 try {
647 const value = await promise;
648 fail(`expected promise to reject, but it resolved with ${stringify(value)}`);
649 } catch (error) {
650 if (error instanceof AssertionError) throw error;
651 return error;
652 }
653 };
654 return new Proxy({} as PromiseMatchers<A>, {
655 get(_target, prop) {
656 if (prop === "not") return makePromiseMatchers(actual, !negated, kind);
657 if (prop === "then") return undefined;
658 return (...args: Array<unknown>) =>
659 settle().then((value) => {
660 const matchers = makeMatchers(value, negated) as any;
661 return matchers[prop](...args);
662 });
663 },
664 });
665 };
666
667 // ---------------------------------------------------------------------------
668 // expect
669 // ---------------------------------------------------------------------------
670
671 export interface Expect {
672 <A>(actual: A, message?: string): Matchers<A>;
673 any(ctor: any): any;
674 anything(): any;
675 arrayContaining(items: ReadonlyArray<unknown>): any;
676 objectContaining(subset: Record<string, unknown>): any;
677 stringContaining(substring: string): any;
678 stringMatching(pattern: string | RegExp): any;
679 toSatisfy(predicate: (value: any) => boolean, description?: string): any;
680 fail(message?: string): never;
681 }
682
683 export const expect: Expect = Object.assign(
684 <A>(actual: A, _message?: string): Matchers<A> => makeMatchers(actual, false),
685 {
686 any: anyMatcher,
687 anything: () => asymmetric("Anything", (actual) => actual !== null && actual !== undefined),
688 arrayContaining: (items: ReadonlyArray<unknown>) =>
689 asymmetric(
690 `ArrayContaining ${stringify(items)}`,
691 (actual) =>
692 Array.isArray(actual) && items.every((item) => actual.some((v) => equals(v, item))),
693 ),
694 objectContaining: (subset: Record<string, unknown>) =>
695 asymmetric(`ObjectContaining ${stringify(subset)}`, (actual) =>
696 matchesObject(actual, subset, new Map()),
697 ),
698 stringContaining: (substring: string) =>
699 asymmetric(
700 `StringContaining ${JSON.stringify(substring)}`,
701 (actual) => typeof actual === "string" && actual.includes(substring),
702 ),
703 stringMatching: (pattern: string | RegExp) =>
704 asymmetric(`StringMatching ${String(pattern)}`, (actual) => {
705 if (typeof actual !== "string") return false;
706 return typeof pattern === "string" ? actual.includes(pattern) : pattern.test(actual);
707 }),
708 toSatisfy: (predicate: (value: any) => boolean, description?: string) =>
709 asymmetric(`Satisfies ${description ?? predicate.name ?? "predicate"}`, (actual) =>
710 predicate(actual),
711 ),
712 fail: (message?: string): never => {
713 throw new AssertionError(message ?? "expect.fail()");
714 },
715 },
716 );
717
718 // ---------------------------------------------------------------------------
719 // assert
720 // ---------------------------------------------------------------------------
721
722 export interface Assert {
723 (condition: unknown, message?: string): asserts condition;
724 strictEqual(actual: unknown, expected: unknown, message?: string): void;
725 deepStrictEqual(actual: unknown, expected: unknown, message?: string): void;
726 isDefined<A>(value: A): asserts value is NonNullable<A>;
727 fail(message?: string): never;
728 }
729
730 const assertFn = (condition: unknown, message?: string): asserts condition => {
731 if (!condition) {
732 throw new AssertionError(message ?? "assertion failed");
733 }
734 };
735
736 export const assert: Assert = Object.assign(assertFn, {
737 strictEqual: (actual: unknown, expected: unknown, message?: string) => {
738 if (!Object.is(actual, expected)) {
739 throw new AssertionError(
740 message ?? `expected ${stringify(actual)} to be ${stringify(expected)}`,
741 actual,
742 expected,
743 );
744 }
745 },
746 deepStrictEqual: (actual: unknown, expected: unknown, message?: string) => {
747 if (!equals(actual, expected, true)) {
748 throw new AssertionError(
749 message ?? `expected ${stringify(actual)} to deep equal ${stringify(expected)}`,
750 actual,
751 expected,
752 );
753 }
754 },
755 isDefined: <A>(value: A): asserts value is NonNullable<A> => {
756 if (value === null || value === undefined) {
757 throw new AssertionError(`expected value to be defined`);
758 }
759 },
760 fail: (message?: string): never => {
761 throw new AssertionError(message ?? "assert.fail()");
762 },
763 }) as Assert;