Repository navigation
Expand file tree
/
Copy pathtest-runner.js
More file actions
270 lines (243 loc) · 9.18 KB
/
Copy pathtest-runner.js
File metadata and controls
270 lines (243 loc) · 9.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
/**
* Simple Test Runner
* Zero-dependency test framework for browser-based testing
*/
class TestRunner {
constructor() {
this.tests = [];
this.results = {
passed: 0,
failed: 0,
total: 0,
// One record per failed test. The console stream is for reading
// along; this is what a driver reads back, so a failure can never
// be lost to console ordering.
failures: []
};
}
/**
* Define a test suite
*/
describe(name, fn) {
const suite = { name, tests: [] };
const context = {
it: (testName, testFn) => {
suite.tests.push({ name: testName, fn: testFn });
}
};
fn.call(context, context.it);
this.tests.push(suite);
}
/**
* Run all tests
*/
async run() {
console.log('🧪 Running tests...\n');
for (const suite of this.tests) {
console.log(`\n📦 ${suite.name}`);
for (const test of suite.tests) {
this.results.total++;
try {
// Check if test expects a 'done' callback (has parameters)
if (test.fn.length > 0) {
// Async test with done callback
await new Promise((resolve, reject) => {
let completed = false;
const done = (err) => {
if (completed) return; // Already called
completed = true;
clearTimeout(timeout);
if (err) reject(err);
else resolve();
};
// Set a timeout to prevent hanging
const timeout = setTimeout(() => {
if (!completed) {
completed = true;
reject(new Error('Test timeout: done() was not called within 5 seconds'));
}
}, 5000);
// Call test with done callback
try {
test.fn(done);
} catch (error) {
if (!completed) {
completed = true;
clearTimeout(timeout);
reject(error);
}
}
});
} else {
// Regular async test or sync test
await test.fn();
}
this.results.passed++;
console.log(` ✅ ${test.name}`);
} catch (error) {
this.results.failed++;
this.results.failures.push({
suite: suite.name,
name: test.name,
message: error.message,
expected: error.expected === undefined ? undefined : safeShow(error.expected),
actual: error.expected === undefined ? undefined : safeShow(error.actual)
});
console.error(` ❌ ${test.name}`);
console.error(` ${error.message}`);
if (error.expected !== undefined) {
console.error(` Expected: ${JSON.stringify(error.expected)}`);
console.error(` Received: ${JSON.stringify(error.actual)}`);
}
}
}
}
this._printSummary();
}
_printSummary() {
console.log('\n' + '='.repeat(50));
console.log(`\n📊 Test Results:`);
console.log(` Total: ${this.results.total}`);
console.log(` ✅ Passed: ${this.results.passed}`);
console.log(` ❌ Failed: ${this.results.failed}`);
const rate = this.results.total > 0
? Math.round((this.results.passed / this.results.total) * 100)
: 0;
console.log(` Success Rate: ${rate}%`);
if (this.results.failed === 0) {
console.log('\n🎉 All tests passed!');
} else {
console.log('\n💥 Some tests failed');
// Repeated at the end so a failure is not buried under several
// hundred passing lines above it.
console.error(`\nFailures (${this.results.failures.length}):`);
for (const f of this.results.failures) {
console.error(` ❌ ${f.suite} > ${f.name}`);
console.error(` ${f.message}`);
}
}
}
/**
* Render results to DOM
*/
renderResults(container) {
const html = `
<div class="test-results">
<h2>Test Results</h2>
<div class="summary ${this.results.failed === 0 ? 'success' : 'failure'}">
<div class="stat">
<span class="label">Total:</span>
<span class="value">${this.results.total}</span>
</div>
<div class="stat">
<span class="label">Passed:</span>
<span class="value">${this.results.passed}</span>
</div>
<div class="stat">
<span class="label">Failed:</span>
<span class="value">${this.results.failed}</span>
</div>
<div class="stat">
<span class="label">Success Rate:</span>
<span class="value">${Math.round((this.results.passed / this.results.total) * 100)}%</span>
</div>
</div>
</div>
`;
container.innerHTML = html;
}
}
// Failure records cross a page boundary (puppeteer serialises them), so
// values are rendered to text here rather than carried as objects.
function safeShow(v) {
if (typeof v === 'function') return '<function>';
try { return JSON.stringify(v); } catch { return String(v); }
}
/**
* Assertion helpers
*/
export const assert = {
equal(actual, expected, message = '') {
if (actual !== expected) {
const error = new Error(message || `Expected ${expected}, got ${actual}`);
error.expected = expected;
error.actual = actual;
throw error;
}
},
deepEqual(actual, expected, message = '') {
const actualStr = JSON.stringify(actual);
const expectedStr = JSON.stringify(expected);
if (actualStr !== expectedStr) {
const error = new Error(message || 'Deep equality failed');
error.expected = expected;
error.actual = actual;
throw error;
}
},
ok(value, message = '') {
if (!value) {
throw new Error(message || `Expected truthy value, got ${value}`);
}
},
throws(fn, expectedError, message = '') {
let thrown = false;
try {
fn();
} catch (error) {
thrown = true;
if (expectedError && !(error instanceof expectedError)) {
throw new Error(message || `Expected ${expectedError.name}, got ${error.constructor.name}`);
}
}
if (!thrown) {
throw new Error(message || 'Expected function to throw');
}
},
async rejects(promise, expectedError, message = '') {
let thrown = false;
try {
await promise;
} catch (error) {
thrown = true;
if (expectedError && !(error instanceof expectedError)) {
throw new Error(message || `Expected ${expectedError.name}, got ${error.constructor.name}`);
}
}
if (!thrown) {
throw new Error(message || 'Expected promise to reject');
}
},
isType(value, type, message = '') {
if (typeof value !== type) {
throw new Error(message || `Expected type ${type}, got ${typeof value}`);
}
},
includes(array, value, message = '') {
if (!array.includes(value)) {
throw new Error(message || `Expected array to include ${value}`);
}
},
isNull(value, message = '') {
if (value !== null) {
throw new Error(message || `Expected null, got ${value}`);
}
},
isNotNull(value, message = '') {
if (value === null) {
throw new Error(message || 'Expected non-null value');
}
},
notEqual(actual, expected, message = '') {
if (actual === expected) {
const error = new Error(message || `Expected values to be different, but both were ${actual}`);
error.expected = `not ${expected}`;
error.actual = actual;
throw error;
}
}
};
// Global test runner instance
export const runner = new TestRunner();
// Convenience export
export const describe = runner.describe.bind(runner);