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