Open History to see the last commit
1type AsyncCallback = () => void | Promise<void>
2
3type TestNode = {
4 name: string
5 fn: AsyncCallback
6 skipped: boolean
7}
8
9type SuiteNode = {
10 name: string
11 suites: Array<SuiteNode>
12 tests: Array<TestNode>
13 beforeAllHooks: Array<AsyncCallback>
14 afterAllHooks: Array<AsyncCallback>
15 beforeEachHooks: Array<AsyncCallback>
16 afterEachHooks: Array<AsyncCallback>
17 skipped: boolean
18}
19
20type TestResult = {
21 name: string
22 kind: `test` | `hook`
23 status: `passed` | `failed` | `skipped` | `unexecuted`
24 executed: boolean
25 error?: string
26}
27
28export type RegisteredTestRunResult = {
29 passed: number
30 failed: number
31 skipped: number
32 total: number
33 results: Array<TestResult>
34 complete: boolean
35 expected: number
36 registered: number
37 executed: number
38 unexecuted: number
39 expectedNames: Array<string>
40 registeredNames: Array<string>
41 executedNames: Array<string>
42 skippedNames: Array<string>
43 unexecutedNames: Array<string>
44 missingNames: Array<string>
45 unexpectedNames: Array<string>
46 duplicateNames: Array<string>
47 manifestErrors: Array<string>
48}
49
50type NativeMatchers = {
51 toBe: (expected: unknown) => void
52 toEqual: (expected: unknown) => void
53 toStrictEqual: (expected: unknown) => void
54 toThrow: () => void
55 toBeGreaterThan: (expected: number) => void
56 toBeGreaterThanOrEqual: (expected: number) => void
57 toBeLessThan: (expected: number) => void
58 toBeLessThanOrEqual: (expected: number) => void
59 toBeTruthy: () => void
60 toBeDefined: () => void
61 toBeNull: () => void
62 toContain: (expected: unknown) => void
63 toHaveProperty: (propertyKey: string) => void
64 toHaveLength: (expected: number) => void
65 not: NativeMatchers
66}
67
68function createSuite(name: string, skipped = false): SuiteNode {
69 return {
70 name,
71 suites: [],
72 tests: [],
73 beforeAllHooks: [],
74 afterAllHooks: [],
75 beforeEachHooks: [],
76 afterEachHooks: [],
77 skipped,
78 }
79}
80
81const rootSuite = createSuite(``)
82function formatSuitePath(
83 suites: ReadonlyArray<SuiteNode>,
84 leafName?: string,
85): string {
86 const segments = suites
87 .map((suite) => suite.name)
88 .filter((name) => name.length > 0)
89 if (leafName && leafName.length > 0) {
90 segments.push(leafName)
91 }
92
93 return segments.join(` > `)
94}
95
96let suiteStack: Array<SuiteNode> = [rootSuite]
97
98function currentSuite(): SuiteNode {
99 return suiteStack[suiteStack.length - 1] ?? rootSuite
100}
101
102function pushSuite(
103 name: string,
104 skipped: boolean,
105 callback: AsyncCallback,
106): void {
107 const suite = createSuite(name, skipped)
108 currentSuite().suites.push(suite)
109
110 // Collect skipped declarations too; their test bodies and hooks never run.
111 suiteStack.push(suite)
112 try {
113 callback()
114 } finally {
115 suiteStack.pop()
116 }
117}
118
119function registerHook(
120 key:
121 | `beforeAllHooks`
122 | `afterAllHooks`
123 | `beforeEachHooks`
124 | `afterEachHooks`,
125 callback: AsyncCallback,
126): void {
127 currentSuite()[key].push(callback)
128}
129
130function resolveTestCallback(
131 callbackOrOptions: AsyncCallback | Record<string, unknown>,
132 maybeCallback?: AsyncCallback,
133): AsyncCallback {
134 if (typeof callbackOrOptions === `function`) {
135 return callbackOrOptions
136 }
137
138 if (typeof maybeCallback === `function`) {
139 return maybeCallback
140 }
141
142 throw new Error(`Test callback must be a function`)
143}
144
145function registerTest(
146 name: string,
147 callback: AsyncCallback,
148 skipped: boolean,
149): void {
150 currentSuite().tests.push({
151 name,
152 fn: callback,
153 skipped,
154 })
155}
156
157function formatValue(value: unknown): string {
158 if (typeof value === `string`) {
159 return value
160 }
161
162 return JSON.stringify(
163 value,
164 (_, nestedValue) =>
165 typeof nestedValue === `bigint`
166 ? { __type: `bigint`, value: nestedValue.toString() }
167 : nestedValue,
168 2,
169 )
170}
171
172function isObjectLike(value: unknown): value is Record<string, unknown> {
173 return typeof value === `object` && value !== null
174}
175
176function deepEqual(left: unknown, right: unknown): boolean {
177 if (Object.is(left, right)) {
178 return true
179 }
180
181 if (left instanceof Date && right instanceof Date) {
182 return left.getTime() === right.getTime()
183 }
184
185 if (Array.isArray(left) && Array.isArray(right)) {
186 return (
187 left.length === right.length &&
188 left.every((value, index) => deepEqual(value, right[index]))
189 )
190 }
191
192 if (isObjectLike(left) && isObjectLike(right)) {
193 const leftKeys = Object.keys(left)
194 const rightKeys = Object.keys(right)
195
196 return (
197 leftKeys.length === rightKeys.length &&
198 leftKeys.every(
199 (key) =>
200 Object.prototype.hasOwnProperty.call(right, key) &&
201 deepEqual(left[key], right[key]),
202 )
203 )
204 }
205
206 return false
207}
208
209// The shared native fixture uses primitives, Dates, arrays and plain metadata.
210// Keep own-key/hole/kind distinctions; do not silently treat other objects as {}.
211function strictEqual(left: unknown, right: unknown): boolean {
212 if (Object.is(left, right)) return true
213 if (left instanceof Date || right instanceof Date) {
214 return (
215 left instanceof Date &&
216 right instanceof Date &&
217 Object.is(left.getTime(), right.getTime())
218 )
219 }
220 if (!isObjectLike(left) || !isObjectLike(right)) return false
221 if (Array.isArray(left) !== Array.isArray(right)) return false
222 if (Object.getPrototypeOf(left) !== Object.getPrototypeOf(right)) return false
223 if (
224 Array.isArray(left) &&
225 Array.isArray(right) &&
226 left.length !== right.length
227 )
228 return false
229 const prototype = Object.getPrototypeOf(left)
230 if (
231 prototype !== Object.prototype &&
232 prototype !== null &&
233 prototype !== Array.prototype
234 )
235 throw new Error('Unsupported object kind in native strict matcher')
236 const keys = (value: object) =>
237 Reflect.ownKeys(value).filter((key) =>
238 Object.prototype.propertyIsEnumerable.call(value, key),
239 )
240 const leftKeys = keys(left)
241 const rightKeys = keys(right)
242 return (
243 leftKeys.length === rightKeys.length &&
244 leftKeys.every(
245 (key) =>
246 Object.prototype.propertyIsEnumerable.call(right, key) &&
247 strictEqual(Reflect.get(left, key), Reflect.get(right, key)),
248 )
249 )
250}
251
252function failExpectation(message: string | undefined, fallback: string): never {
253 throw new Error(message ?? fallback)
254}
255
256function createMatchers(
257 actual: unknown,
258 message?: string,
259 negate = false,
260): NativeMatchers {
261 const assert = (condition: boolean, failureMessage: string): void => {
262 const shouldFail = negate ? condition : !condition
263 if (shouldFail) {
264 failExpectation(message, failureMessage)
265 }
266 }
267
268 const matchers = {
269 toBe(expected: unknown) {
270 assert(
271 Object.is(actual, expected),
272 `Expected ${formatValue(actual)} ${negate ? `not ` : ``}to be ${formatValue(expected)}`,
273 )
274 },
275 toEqual(expected: unknown) {
276 assert(
277 deepEqual(actual, expected),
278 `Expected ${formatValue(actual)} ${negate ? `not ` : ``}to equal ${formatValue(expected)}`,
279 )
280 },
281 toStrictEqual(expected: unknown) {
282 assert(
283 strictEqual(actual, expected),
284 `Expected ${formatValue(actual)} ${negate ? `not ` : ``}to strictly equal ${formatValue(expected)}`,
285 )
286 },
287 toThrow(...args: Array<unknown>) {
288 if (args.length > 0)
289 throw new Error('Native toThrow supports no-argument assertions only')
290 if (typeof actual !== 'function')
291 throw new Error('toThrow requires a synchronous function')
292 let threw = false
293 let result: unknown
294 try {
295 result = actual()
296 } catch {
297 threw = true
298 }
299 if (
300 !threw &&
301 result !== null &&
302 (typeof result === 'object' || typeof result === 'function') &&
303 typeof Reflect.get(result, 'then') === 'function'
304 ) {
305 void Promise.resolve(result).catch(() => {})
306 throw new Error('Native toThrow does not support async functions')
307 }
308 assert(threw, `Expected function ${negate ? `not ` : ``}to throw`)
309 },
310 toBeGreaterThan(expected: number) {
311 assert(
312 typeof actual === `number` && actual > expected,
313 `Expected ${formatValue(actual)} ${negate ? `not ` : ``}to be greater than ${String(expected)}`,
314 )
315 },
316 toBeGreaterThanOrEqual(expected: number) {
317 assert(
318 typeof actual === `number` && actual >= expected,
319 `Expected ${formatValue(actual)} ${negate ? `not ` : ``}to be greater than or equal to ${String(expected)}`,
320 )
321 },
322 toBeLessThan(expected: number) {
323 assert(
324 typeof actual === `number` && actual < expected,
325 `Expected ${formatValue(actual)} ${negate ? `not ` : ``}to be less than ${String(expected)}`,
326 )
327 },
328 toBeLessThanOrEqual(expected: number) {
329 assert(
330 typeof actual === `number` && actual <= expected,
331 `Expected ${formatValue(actual)} ${negate ? `not ` : ``}to be less than or equal to ${String(expected)}`,
332 )
333 },
334 toBeTruthy() {
335 assert(
336 Boolean(actual),
337 `Expected ${formatValue(actual)} ${negate ? `not ` : ``}to be truthy`,
338 )
339 },
340 toBeDefined() {
341 assert(
342 actual !== undefined,
343 `Expected ${formatValue(actual)} ${negate ? `not ` : ``}to be defined`,
344 )
345 },
346 toBeNull() {
347 assert(
348 actual === null,
349 `Expected ${formatValue(actual)} ${negate ? `not ` : ``}to be null`,
350 )
351 },
352 toContain(expected: unknown) {
353 const contains =
354 typeof actual === `string`
355 ? actual.includes(String(expected))
356 : Array.isArray(actual)
357 ? actual.some((entry) => deepEqual(entry, expected))
358 : false
359
360 assert(
361 contains,
362 `Expected ${formatValue(actual)} ${negate ? `not ` : ``}to contain ${formatValue(expected)}`,
363 )
364 },
365 toHaveProperty(propertyKey: string) {
366 const hasProperty =
367 isObjectLike(actual) &&
368 Object.prototype.hasOwnProperty.call(actual, propertyKey)
369
370 assert(
371 hasProperty,
372 `Expected ${formatValue(actual)} ${negate ? `not ` : ``}to have property ${propertyKey}`,
373 )
374 },
375 toHaveLength(expected: number) {
376 const actualLength =
377 typeof actual === `string` || Array.isArray(actual)
378 ? actual.length
379 : undefined
380
381 assert(
382 actualLength === expected,
383 `Expected ${formatValue(actual)} ${negate ? `not ` : ``}to have length ${String(expected)}`,
384 )
385 },
386 } satisfies Omit<NativeMatchers, 'not'>
387
388 return new Proxy(matchers, {
389 get(target, propertyKey, receiver) {
390 if (propertyKey === `not`) {
391 return createMatchers(actual, message, !negate)
392 }
393
394 return Reflect.get(target, propertyKey, receiver)
395 },
396 }) as NativeMatchers
397}
398
399export function expect(actual: unknown, message?: string): NativeMatchers {
400 return createMatchers(actual, message)
401}
402
403export const vi = {
404 async waitFor<T>(
405 callback: () => T,
406 options: { timeout?: number; interval?: number } = {},
407 ): Promise<T> {
408 if (
409 typeof callback !== 'function' ||
410 !isObjectLike(options) ||
411 Array.isArray(options)
412 )
413 throw new Error(
414 'Native waitFor requires a callback and an options object',
415 )
416 if (
417 Object.keys(options).some(
418 (key) => key !== 'timeout' && key !== 'interval',
419 )
420 )
421 throw new Error('Unsupported native waitFor option')
422 const timeout = options.timeout ?? 1000
423 const interval = options.interval ?? 50
424 if (
425 !Number.isFinite(timeout) ||
426 timeout < 0 ||
427 !Number.isFinite(interval) ||
428 interval <= 0
429 )
430 throw new Error('Invalid native waitFor timeout or interval')
431 const started = Date.now()
432 for (;;) {
433 let result: T
434 try {
435 result = callback()
436 } catch (error) {
437 const remaining = timeout - (Date.now() - started)
438 if (remaining <= 0) throw error
439 await new Promise<void>((resolve) =>
440 setTimeout(resolve, Math.min(interval, remaining)),
441 )
442 continue
443 }
444 if (
445 result !== null &&
446 (typeof result === 'object' || typeof result === 'function') &&
447 typeof Reflect.get(result, 'then') === 'function'
448 ) {
449 void Promise.resolve(result).catch(() => {})
450 throw new Error(
451 'Native waitFor supports synchronous assertion callbacks only',
452 )
453 }
454 return result
455 }
456 },
457}
458
459type Describe = ((name: string, callback: AsyncCallback) => void) & {
460 skip: (name: string, callback: AsyncCallback) => void
461}
462
463type It = ((
464 name: string,
465 callbackOrOptions: AsyncCallback | Record<string, unknown>,
466 maybeCallback?: AsyncCallback,
467) => void) & {
468 skip: (
469 name: string,
470 callbackOrOptions: AsyncCallback | Record<string, unknown>,
471 maybeCallback?: AsyncCallback,
472 ) => void
473}
474
475export const describe: Describe = Object.assign(
476 (name: string, callback: AsyncCallback) => {
477 pushSuite(name, false, callback)
478 },
479 {
480 skip: (name: string, callback: AsyncCallback) => {
481 pushSuite(name, true, callback)
482 },
483 },
484)
485
486export const it: It = Object.assign(
487 (
488 name: string,
489 callbackOrOptions: AsyncCallback | Record<string, unknown>,
490 maybeCallback?: AsyncCallback,
491 ) => {
492 registerTest(
493 name,
494 resolveTestCallback(callbackOrOptions, maybeCallback),
495 false,
496 )
497 },
498 {
499 skip: (
500 name: string,
501 callbackOrOptions: AsyncCallback | Record<string, unknown>,
502 maybeCallback?: AsyncCallback,
503 ) => {
504 registerTest(
505 name,
506 resolveTestCallback(callbackOrOptions, maybeCallback),
507 true,
508 )
509 },
510 },
511)
512
513export const test = it
514
515export function beforeAll(callback: AsyncCallback): void {
516 registerHook(`beforeAllHooks`, callback)
517}
518
519export function afterAll(callback: AsyncCallback): void {
520 registerHook(`afterAllHooks`, callback)
521}
522
523export function beforeEach(callback: AsyncCallback): void {
524 registerHook(`beforeEachHooks`, callback)
525}
526
527export function afterEach(callback: AsyncCallback): void {
528 registerHook(`afterEachHooks`, callback)
529}
530
531export function resetRegisteredTests(): void {
532 rootSuite.suites = []
533 rootSuite.tests = []
534 rootSuite.beforeAllHooks = []
535 rootSuite.afterAllHooks = []
536 rootSuite.beforeEachHooks = []
537 rootSuite.afterEachHooks = []
538 suiteStack = [rootSuite]
539}
540
541function collectTests(
542 suite: SuiteNode,
543 ancestors: Array<SuiteNode> = [],
544 inheritedSkip = false,
545): Array<{ name: string; skipped: boolean }> {
546 const path = [...ancestors, suite]
547 const skipped = inheritedSkip || suite.skipped
548 return [
549 ...suite.tests.map((testNode) => ({
550 name: formatSuitePath(path, testNode.name),
551 skipped: skipped || testNode.skipped,
552 })),
553 ...suite.suites.flatMap((child) => collectTests(child, path, skipped)),
554 ]
555}
556
557export function getRegisteredTestNames(): Array<string> {
558 return collectTests(rootSuite).map((testNode) => testNode.name)
559}
560
561export function getRegisteredTestCount(): number {
562 return getRegisteredTestNames().length
563}
564
565function recordUnexecuted(
566 suite: SuiteNode,
567 ancestors: Array<SuiteNode>,
568 results: Array<TestResult>,
569): void {
570 for (const testNode of collectTests(suite, ancestors)) {
571 results.push({
572 name: testNode.name,
573 kind: 'test',
574 status: testNode.skipped ? 'skipped' : 'unexecuted',
575 executed: false,
576 })
577 }
578}
579
580async function runHookList(
581 hooks: ReadonlyArray<AsyncCallback>,
582 label: string,
583 results: Array<TestResult>,
584 stopOnFailure: boolean,
585): Promise<boolean> {
586 let succeeded = true
587 for (const [index, hook] of hooks.entries()) {
588 try {
589 await hook()
590 } catch (error) {
591 succeeded = false
592 results.push({
593 name: `${label} [${index + 1}]`,
594 kind: 'hook',
595 status: 'failed',
596 executed: false,
597 error: error instanceof Error ? error.message : String(error),
598 })
599 if (stopOnFailure) break
600 }
601 }
602 return succeeded
603}
604
605type RunOptions = {
606 expectedTestNames: ReadonlyArray<string>
607 onTestStart?: (context: {
608 name: string
609 index: number
610 total: number
611 }) => void
612}
613
614async function runSuite(
615 suite: SuiteNode,
616 ancestors: Array<SuiteNode>,
617 results: Array<TestResult>,
618 state: { index: number; total: number },
619 options: RunOptions,
620): Promise<void> {
621 if (suite.skipped) {
622 recordUnexecuted(suite, ancestors, results)
623 return
624 }
625 const path = [...ancestors, suite]
626 const started = await runHookList(
627 suite.beforeAllHooks,
628 `${formatSuitePath(path)} beforeAll`,
629 results,
630 true,
631 )
632 if (!started) {
633 recordUnexecuted(suite, ancestors, results)
634 } else {
635 for (const testNode of suite.tests) {
636 const name = formatSuitePath(path, testNode.name)
637 state.index++
638 if (testNode.skipped) {
639 results.push({ name, kind: 'test', status: 'skipped', executed: false })
640 continue
641 }
642 let ready = true
643 try {
644 try {
645 options.onTestStart?.({
646 name,
647 index: state.index,
648 total: state.total,
649 })
650 } catch (error) {
651 ready = false
652 results.push({
653 name: `${name} onTestStart`,
654 kind: 'hook',
655 status: 'failed',
656 executed: false,
657 error: error instanceof Error ? error.message : String(error),
658 })
659 }
660 if (ready) {
661 for (const entry of path) {
662 ready = await runHookList(
663 entry.beforeEachHooks,
664 `${name} beforeEach (${formatSuitePath(path.slice(0, path.indexOf(entry) + 1))})`,
665 results,
666 true,
667 )
668 if (!ready) break
669 }
670 }
671 if (!ready) {
672 results.push({
673 name,
674 kind: 'test',
675 status: 'unexecuted',
676 executed: false,
677 })
678 } else {
679 try {
680 await testNode.fn()
681 results.push({
682 name,
683 kind: 'test',
684 status: 'passed',
685 executed: true,
686 })
687 } catch (error) {
688 results.push({
689 name,
690 kind: 'test',
691 status: 'failed',
692 executed: true,
693 error: error instanceof Error ? error.message : String(error),
694 })
695 }
696 }
697 } finally {
698 for (const entry of [...path].reverse()) {
699 await runHookList(
700 entry.afterEachHooks,
701 `${name} afterEach (${formatSuitePath(path.slice(0, path.indexOf(entry) + 1))})`,
702 results,
703 false,
704 )
705 }
706 }
707 }
708 for (const child of suite.suites)
709 await runSuite(child, path, results, state, options)
710 }
711 await runHookList(
712 suite.afterAllHooks,
713 `${formatSuitePath(path)} afterAll`,
714 results,
715 false,
716 )
717}
718
719function duplicates(names: ReadonlyArray<string>): Array<string> {
720 const seen = new Set<string>()
721 const repeated = new Set<string>()
722 for (const name of names) {
723 if (seen.has(name)) repeated.add(name)
724 seen.add(name)
725 }
726 return [...repeated]
727}
728
729export async function runRegisteredTests(
730 options: RunOptions,
731): Promise<RegisteredTestRunResult> {
732 const expectedNames = [...options.expectedTestNames]
733 const initialNames = getRegisteredTestNames()
734 const results: Array<TestResult> = []
735 await runSuite(
736 rootSuite,
737 [],
738 results,
739 { index: 0, total: initialNames.length },
740 options,
741 )
742 const registeredNames = getRegisteredTestNames()
743 const tests = results.filter((result) => result.kind === 'test')
744 const executedNames = tests
745 .filter((result) => result.executed)
746 .map((result) => result.name)
747 const skippedNames = tests
748 .filter((result) => result.status === 'skipped')
749 .map((result) => result.name)
750 const unexecutedNames = tests
751 .filter((result) => result.status === 'unexecuted')
752 .map((result) => result.name)
753 const expectedSet = new Set(expectedNames)
754 const registeredSet = new Set(registeredNames)
755 const executedSet = new Set(executedNames)
756 const missingNames = expectedNames.filter((name) => !registeredSet.has(name))
757 const unexpectedNames = registeredNames.filter(
758 (name) => !expectedSet.has(name),
759 )
760 const duplicateNames = duplicates(registeredNames)
761 const manifestErrors: Array<string> = []
762 if (expectedNames.length === 0)
763 manifestErrors.push('Expected law manifest is empty')
764 if (
765 expectedNames.some(
766 (name) => typeof name !== 'string' || name.trim().length === 0,
767 )
768 )
769 manifestErrors.push('Expected law manifest has an invalid name')
770 if (duplicates(expectedNames).length > 0)
771 manifestErrors.push('Expected law manifest has duplicate names')
772 if (missingNames.length > 0)
773 manifestErrors.push('Required laws are not registered')
774 if (unexpectedNames.length > 0)
775 manifestErrors.push('Unexpected laws are registered')
776 if (duplicateNames.length > 0)
777 manifestErrors.push('Law registration has duplicate names')
778 if (
779 expectedNames.some((name) => !executedSet.has(name)) ||
780 executedNames.length !== expectedNames.length ||
781 duplicates(executedNames).length > 0
782 )
783 manifestErrors.push(
784 'Required law bodies were not each executed exactly once',
785 )
786 if (skippedNames.length > 0 || unexecutedNames.length > 0)
787 manifestErrors.push('Registered laws were skipped or unexecuted')
788 if (
789 initialNames.length !== registeredNames.length ||
790 initialNames.some((name, index) => name !== registeredNames[index])
791 )
792 manifestErrors.push('Law registration changed during execution')
793 return {
794 passed: tests.filter((result) => result.status === 'passed').length,
795 failed: results.filter((result) => result.status === 'failed').length,
796 skipped: skippedNames.length,
797 total: registeredNames.length,
798 results,
799 complete: manifestErrors.length === 0,
800 expected: expectedNames.length,
801 registered: registeredNames.length,
802 executed: executedNames.length,
803 unexecuted: unexecutedNames.length,
804 expectedNames,
805 registeredNames,
806 executedNames,
807 skippedNames,
808 unexecutedNames,
809 missingNames,
810 unexpectedNames,
811 duplicateNames,
812 manifestErrors,
813 }
814}