Debian Codegraph @

debian/tests/test_modules/vitest/index.js

raw
1 import assert from "node:assert/strict"
2 import { createRequire } from "node:module"
3 import { isDeepStrictEqual } from "node:util"
4
5 const require = createRequire(import.meta.url)
6 const { JSDOM } = require("jsdom")
7
8 const dom = new JSDOM("<!doctype html><html><body></body></html>", {
9 url: "https://example.invalid/",
10 })
11
12 globalThis.window = dom.window
13 globalThis.document = dom.window.document
14 Object.defineProperty(globalThis, "navigator", {
15 configurable: true,
16 value: dom.window.navigator,
17 })
18 globalThis.HTMLElement = dom.window.HTMLElement
19 globalThis.Event = dom.window.Event
20 globalThis.CompositionEvent = dom.window.CompositionEvent
21
22 const modifierFields = {
23 Alt: "altKey",
24 AltGraph: "modifierAltGraph",
25 Control: "ctrlKey",
26 Meta: "metaKey",
27 Shift: "shiftKey",
28 }
29
30 globalThis.KeyboardEvent = class KeyboardEvent extends dom.window.KeyboardEvent {
31 #modifiers
32
33 constructor(type, init = {}) {
34 super(type, init)
35 this.#modifiers = { ...init }
36 }
37
38 getModifierState(modifier) {
39 let field = modifierFields[modifier]
40 return field ? Boolean(this.#modifiers[field]) : false
41 }
42 }
43
44 const tests = []
45 const describeStack = []
46 let currentCleanups = null
47 let spies = []
48
49 function fullName(name) {
50 return [...describeStack, name].join(" > ")
51 }
52
53 export function test(name, fn) {
54 tests.push({ name: fullName(name), fn })
55 }
56
57 test.describe = (name, fn) => {
58 describeStack.push(name)
59 try {
60 fn()
61 } finally {
62 describeStack.pop()
63 }
64 }
65
66 export function onTestFinished(fn) {
67 if (!currentCleanups) {
68 throw new Error("onTestFinished() called outside a test")
69 }
70 currentCleanups.push(fn)
71 }
72
73 function makeMock(implementation = () => undefined) {
74 function mock(...args) {
75 mock.mock.calls.push(args)
76 return implementation.apply(this, args)
77 }
78
79 mock.mock = { calls: [] }
80 mock.mockImplementation = fn => {
81 implementation = fn
82 return mock
83 }
84
85 return mock
86 }
87
88 export const vi = {
89 fn: makeMock,
90 spyOn(object, property) {
91 const original = object[property]
92 const mock = makeMock(function (...args) {
93 return original.apply(this, args)
94 })
95 object[property] = mock
96 spies.push(() => {
97 object[property] = original
98 })
99 return mock
100 },
101 }
102
103 function callsOf(actual) {
104 assert.ok(actual?.mock?.calls, "expected a mock function")
105 return actual.mock.calls
106 }
107
108 function formatCalls(calls) {
109 return JSON.stringify(calls)
110 }
111
112 function makeExpectation(actual, negated = false) {
113 function check(condition, message) {
114 if (negated ? condition : !condition) {
115 throw new assert.AssertionError({ message })
116 }
117 }
118
119 return {
120 get not() {
121 return makeExpectation(actual, !negated)
122 },
123 toHaveBeenCalled() {
124 check(callsOf(actual).length > 0, "expected mock to have been called")
125 },
126 toHaveBeenCalledOnce() {
127 let calls = callsOf(actual)
128 check(
129 calls.length === 1,
130 `expected mock to have been called once, got ${calls.length}`,
131 )
132 },
133 toHaveBeenCalledExactlyOnceWith(...expected) {
134 let calls = callsOf(actual)
135 check(
136 calls.length === 1 && isDeepStrictEqual(calls[0], expected),
137 `expected one call with ${JSON.stringify(expected)}, got ${formatCalls(calls)}`,
138 )
139 },
140 }
141 }
142
143 export function expect(actual) {
144 return makeExpectation(actual)
145 }
146
147 export async function run() {
148 let failures = 0
149
150 for (let { name, fn } of tests) {
151 currentCleanups = []
152 spies = []
153 try {
154 await fn()
155 console.log(`ok - ${name}`)
156 } catch (error) {
157 failures += 1
158 console.error(`not ok - ${name}`)
159 console.error(error?.stack || error)
160 } finally {
161 for (let cleanup of currentCleanups.reverse()) {
162 await cleanup()
163 }
164 for (let restore of spies.reverse()) {
165 restore()
166 }
167 currentCleanups = null
168 document.body.replaceChildren()
169 }
170 }
171
172 console.log(`${tests.length - failures}/${tests.length} tests passed`)
173 if (failures) {
174 process.exitCode = 1
175 }
176 }