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 status: `passed` | `failed` | `skipped`
23 error?: string
24}
25
26export type RegisteredTestRunResult = {
27 passed: number
28 failed: number
29 skipped: number
30 total: number
31 results: Array<TestResult>
32}
33
34function createSuite(name: string, skipped = false): SuiteNode {
35 return {
36 name,
37 suites: [],
38 tests: [],
39 beforeAllHooks: [],
40 afterAllHooks: [],
41 beforeEachHooks: [],
42 afterEachHooks: [],
43 skipped,
44 }
45}
46
47const rootSuite = createSuite(``)
48function formatSuitePath(
49 suites: ReadonlyArray<SuiteNode>,
50 leafName?: string,
51): string {
52 const segments = suites
53 .map((suite) => suite.name)
54 .filter((name) => name.length > 0)
55 if (leafName && leafName.length > 0) {
56 segments.push(leafName)
57 }
58
59 return segments.join(` > `)
60}
61
62let suiteStack: Array<SuiteNode> = [rootSuite]
63
64function currentSuite(): SuiteNode {
65 return suiteStack[suiteStack.length - 1] ?? rootSuite
66}
67
68function pushSuite(
69 name: string,
70 skipped: boolean,
71 callback: AsyncCallback,
72): void {
73 const suite = createSuite(name, skipped)
74 currentSuite().suites.push(suite)
75
76 if (skipped) {
77 return
78 }
79
80 suiteStack.push(suite)
81 try {
82 callback()
83 } finally {
84 suiteStack.pop()
85 }
86}
87
88function registerHook(
89 key:
90 | `beforeAllHooks`
91 | `afterAllHooks`
92 | `beforeEachHooks`
93 | `afterEachHooks`,
94 callback: AsyncCallback,
95): void {
96 currentSuite()[key].push(callback)
97}
98
99function resolveTestCallback(
100 callbackOrOptions: AsyncCallback | Record<string, unknown>,
101 maybeCallback?: AsyncCallback,
102): AsyncCallback {
103 if (typeof callbackOrOptions === `function`) {
104 return callbackOrOptions
105 }
106
107 if (typeof maybeCallback === `function`) {
108 return maybeCallback
109 }
110
111 throw new Error(`Test callback must be a function`)
112}
113
114function registerTest(
115 name: string,
116 callback: AsyncCallback,
117 skipped: boolean,
118): void {
119 currentSuite().tests.push({
120 name,
121 fn: callback,
122 skipped,
123 })
124}
125
126function formatValue(value: unknown): string {
127 if (typeof value === `string`) {
128 return value
129 }
130
131 return JSON.stringify(
132 value,
133 (_, nestedValue) =>
134 typeof nestedValue === `bigint`
135 ? { __type: `bigint`, value: nestedValue.toString() }
136 : nestedValue,
137 2,
138 )
139}
140
141function isObjectLike(value: unknown): value is Record<string, unknown> {
142 return typeof value === `object` && value !== null
143}
144
145function deepEqual(left: unknown, right: unknown): boolean {
146 if (Object.is(left, right)) {
147 return true
148 }
149
150 if (left instanceof Date && right instanceof Date) {
151 return left.getTime() === right.getTime()
152 }
153
154 if (Array.isArray(left) && Array.isArray(right)) {
155 return (
156 left.length === right.length &&
157 left.every((value, index) => deepEqual(value, right[index]))
158 )
159 }
160
161 if (isObjectLike(left) && isObjectLike(right)) {
162 const leftKeys = Object.keys(left)
163 const rightKeys = Object.keys(right)
164
165 return (
166 leftKeys.length === rightKeys.length &&
167 leftKeys.every(
168 (key) =>
169 Object.prototype.hasOwnProperty.call(right, key) &&
170 deepEqual(left[key], right[key]),
171 )
172 )
173 }
174
175 return false
176}
177
178function failExpectation(message: string | undefined, fallback: string): never {
179 throw new Error(message ?? fallback)
180}
181
182function createMatchers(
183 actual: unknown,
184 message?: string,
185 negate = false,
186): Record<string, unknown> {
187 const assert = (condition: boolean, failureMessage: string): void => {
188 const shouldFail = negate ? condition : !condition
189 if (shouldFail) {
190 failExpectation(message, failureMessage)
191 }
192 }
193
194 const matchers = {
195 toBe(expected: unknown) {
196 assert(
197 Object.is(actual, expected),
198 `Expected ${formatValue(actual)} ${negate ? `not ` : ``}to be ${formatValue(expected)}`,
199 )
200 },
201 toEqual(expected: unknown) {
202 assert(
203 deepEqual(actual, expected),
204 `Expected ${formatValue(actual)} ${negate ? `not ` : ``}to equal ${formatValue(expected)}`,
205 )
206 },
207 toBeGreaterThan(expected: number) {
208 assert(
209 typeof actual === `number` && actual > expected,
210 `Expected ${formatValue(actual)} ${negate ? `not ` : ``}to be greater than ${String(expected)}`,
211 )
212 },
213 toBeGreaterThanOrEqual(expected: number) {
214 assert(
215 typeof actual === `number` && actual >= expected,
216 `Expected ${formatValue(actual)} ${negate ? `not ` : ``}to be greater than or equal to ${String(expected)}`,
217 )
218 },
219 toBeLessThan(expected: number) {
220 assert(
221 typeof actual === `number` && actual < expected,
222 `Expected ${formatValue(actual)} ${negate ? `not ` : ``}to be less than ${String(expected)}`,
223 )
224 },
225 toBeLessThanOrEqual(expected: number) {
226 assert(
227 typeof actual === `number` && actual <= expected,
228 `Expected ${formatValue(actual)} ${negate ? `not ` : ``}to be less than or equal to ${String(expected)}`,
229 )
230 },
231 toBeTruthy() {
232 assert(
233 Boolean(actual),
234 `Expected ${formatValue(actual)} ${negate ? `not ` : ``}to be truthy`,
235 )
236 },
237 toBeDefined() {
238 assert(
239 actual !== undefined,
240 `Expected ${formatValue(actual)} ${negate ? `not ` : ``}to be defined`,
241 )
242 },
243 toBeNull() {
244 assert(
245 actual === null,
246 `Expected ${formatValue(actual)} ${negate ? `not ` : ``}to be null`,
247 )
248 },
249 toContain(expected: unknown) {
250 const contains =
251 typeof actual === `string`
252 ? actual.includes(String(expected))
253 : Array.isArray(actual)
254 ? actual.some((entry) => deepEqual(entry, expected))
255 : false
256
257 assert(
258 contains,
259 `Expected ${formatValue(actual)} ${negate ? `not ` : ``}to contain ${formatValue(expected)}`,
260 )
261 },
262 toHaveProperty(propertyKey: string) {
263 const hasProperty =
264 isObjectLike(actual) &&
265 Object.prototype.hasOwnProperty.call(actual, propertyKey)
266
267 assert(
268 hasProperty,
269 `Expected ${formatValue(actual)} ${negate ? `not ` : ``}to have property ${propertyKey}`,
270 )
271 },
272 toHaveLength(expected: number) {
273 const actualLength =
274 typeof actual === `string` || Array.isArray(actual)
275 ? actual.length
276 : undefined
277
278 assert(
279 actualLength === expected,
280 `Expected ${formatValue(actual)} ${negate ? `not ` : ``}to have length ${String(expected)}`,
281 )
282 },
283 } as Record<string, unknown>
284
285 return new Proxy(matchers, {
286 get(target, propertyKey, receiver) {
287 if (propertyKey === `not`) {
288 return createMatchers(actual, message, !negate)
289 }
290
291 return Reflect.get(target, propertyKey, receiver)
292 },
293 })
294}
295
296export function expect(
297 actual: unknown,
298 message?: string,
299): Record<string, unknown> {
300 return createMatchers(actual, message)
301}
302
303type Describe = ((name: string, callback: AsyncCallback) => void) & {
304 skip: (name: string, callback: AsyncCallback) => void
305}
306
307type It = ((
308 name: string,
309 callbackOrOptions: AsyncCallback | Record<string, unknown>,
310 maybeCallback?: AsyncCallback,
311) => void) & {
312 skip: (
313 name: string,
314 callbackOrOptions: AsyncCallback | Record<string, unknown>,
315 maybeCallback?: AsyncCallback,
316 ) => void
317}
318
319export const describe: Describe = Object.assign(
320 (name: string, callback: AsyncCallback) => {
321 pushSuite(name, false, callback)
322 },
323 {
324 skip: (name: string, callback: AsyncCallback) => {
325 pushSuite(name, true, callback)
326 },
327 },
328)
329
330export const it: It = Object.assign(
331 (
332 name: string,
333 callbackOrOptions: AsyncCallback | Record<string, unknown>,
334 maybeCallback?: AsyncCallback,
335 ) => {
336 registerTest(
337 name,
338 resolveTestCallback(callbackOrOptions, maybeCallback),
339 false,
340 )
341 },
342 {
343 skip: (
344 name: string,
345 callbackOrOptions: AsyncCallback | Record<string, unknown>,
346 maybeCallback?: AsyncCallback,
347 ) => {
348 registerTest(
349 name,
350 resolveTestCallback(callbackOrOptions, maybeCallback),
351 true,
352 )
353 },
354 },
355)
356
357export const test = it
358
359export function beforeAll(callback: AsyncCallback): void {
360 registerHook(`beforeAllHooks`, callback)
361}
362
363export function afterAll(callback: AsyncCallback): void {
364 registerHook(`afterAllHooks`, callback)
365}
366
367export function beforeEach(callback: AsyncCallback): void {
368 registerHook(`beforeEachHooks`, callback)
369}
370
371export function afterEach(callback: AsyncCallback): void {
372 registerHook(`afterEachHooks`, callback)
373}
374
375export function resetRegisteredTests(): void {
376 rootSuite.suites = []
377 rootSuite.tests = []
378 rootSuite.beforeAllHooks = []
379 rootSuite.afterAllHooks = []
380 rootSuite.beforeEachHooks = []
381 rootSuite.afterEachHooks = []
382 suiteStack = [rootSuite]
383}
384
385function countTests(suite: SuiteNode): number {
386 return (
387 suite.tests.length +
388 suite.suites.reduce(
389 (count, childSuite) => count + countTests(childSuite),
390 0,
391 )
392 )
393}
394
395export function getRegisteredTestCount(): number {
396 return countTests(rootSuite)
397}
398
399async function runHookList(
400 hooks: ReadonlyArray<AsyncCallback>,
401 label: string,
402 results: Array<TestResult>,
403): Promise<boolean> {
404 for (const hook of hooks) {
405 try {
406 await hook()
407 } catch (error) {
408 const message = error instanceof Error ? error.message : String(error)
409 results.push({
410 name: label,
411 status: `failed`,
412 error: message,
413 })
414 return false
415 }
416 }
417
418 return true
419}
420
421async function runSuite(
422 suite: SuiteNode,
423 ancestors: Array<SuiteNode>,
424 results: Array<TestResult>,
425 state: {
426 index: number
427 total: number
428 },
429 options: {
430 onTestStart?: (context: {
431 name: string
432 index: number
433 total: number
434 }) => void
435 },
436): Promise<void> {
437 if (suite.skipped) {
438 return
439 }
440
441 const suitePath = [...ancestors, suite]
442 const beforeAllSucceeded = await runHookList(
443 suite.beforeAllHooks,
444 `${formatSuitePath(suitePath)} beforeAll`,
445 results,
446 )
447
448 if (beforeAllSucceeded) {
449 for (const testNode of suite.tests) {
450 const testName = formatSuitePath(suitePath, testNode.name)
451 state.index++
452
453 if (testNode.skipped) {
454 results.push({
455 name: testName,
456 status: `skipped`,
457 })
458 continue
459 }
460
461 options.onTestStart?.({
462 name: testName,
463 index: state.index,
464 total: state.total,
465 })
466
467 try {
468 for (const entry of suitePath) {
469 for (const hook of entry.beforeEachHooks) {
470 await hook()
471 }
472 }
473
474 await testNode.fn()
475 results.push({
476 name: testName,
477 status: `passed`,
478 })
479 } catch (error) {
480 const message = error instanceof Error ? error.message : String(error)
481 results.push({
482 name: testName,
483 status: `failed`,
484 error: message,
485 })
486 } finally {
487 for (const entry of [...suitePath].reverse()) {
488 for (const hook of entry.afterEachHooks) {
489 try {
490 await hook()
491 } catch (error) {
492 const message =
493 error instanceof Error ? error.message : String(error)
494 results.push({
495 name: `${testName} afterEach`,
496 status: `failed`,
497 error: message,
498 })
499 }
500 }
501 }
502 }
503 }
504
505 for (const childSuite of suite.suites) {
506 await runSuite(childSuite, suitePath, results, state, options)
507 }
508 }
509
510 await runHookList(
511 suite.afterAllHooks,
512 `${formatSuitePath(suitePath)} afterAll`,
513 results,
514 )
515}
516
517export async function runRegisteredTests(
518 options: {
519 onTestStart?: (context: {
520 name: string
521 index: number
522 total: number
523 }) => void
524 } = {},
525): Promise<RegisteredTestRunResult> {
526 const results: Array<TestResult> = []
527 const state = {
528 index: 0,
529 total: getRegisteredTestCount(),
530 }
531
532 await runSuite(rootSuite, [], results, state, options)
533
534 const passed = results.filter((result) => result.status === `passed`).length
535 const failed = results.filter((result) => result.status === `failed`).length
536 const skipped = results.filter((result) => result.status === `skipped`).length
537
538 return {
539 passed,
540 failed,
541 skipped,
542 total: results.length,
543 results,
544 }
545}