/
shoulda.js
361 lines (323 loc) · 9.61 KB
/
shoulda.js
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/*
* A unit testing micro framework. Tests are grouped into "contexts", each of which can share
* common setup functions.
*/
/*
* Assertions.
*/
const assert = {
isTrue: function (value) {
if (!value) {
this.fail("Expected true, but got " + value);
}
},
isFalse: function (value) {
if (value) {
this.fail("Expected false, but got " + value);
}
},
// Does a deep-equal check on complex objects.
equal: function (expected, actual) {
const areEqual = typeof expected === "object"
? JSON.stringify(expected) === JSON.stringify(actual)
: expected === actual;
if (!areEqual) {
this.fail(
`\nExpected:\n${this._print(expected)}\nGot:\n${this._print(actual)}\n`,
);
}
},
// We cannot name this function simply "throws", because it's a reserved JavaScript keyword.
throwsError: function (expression, errorName) {
try {
expression();
} catch (error) {
if (errorName) {
if (error.name == errorName) {
return;
} else {
assert.fail(
`Expected error ${errorName} to be thrown but error ${error.name} was thrown instead.`,
);
}
} else {
return;
}
}
if (errorName) {
assert.fail(`Expected error ${errorName} but no error was thrown.`);
} else {
assert.fail("Expected error but none was thrown.");
}
},
fail: function (message) {
throw new AssertionError(message);
},
// Used for printing the arguments passed to assertions.
_print: function (object) {
if (object === null) return "null";
else if (object === undefined) return "undefined";
else if (typeof object === "string") return '"' + object + '"';
else {
try {
// Pretty-print with indentation.
return JSON.stringify(object, undefined, 2);
} catch (_) {
// `object` might not be stringifiable (e.g. DOM nodes), or JSON.stringify may not exist.
return object.toString();
}
}
},
};
/*
* ensureCalled ensures the given function is called by the end of the test case. This is useful
* when testing APIs that use callbacks.
*/
function ensureCalled(fn) {
const wrappedFunction = function () {
const i = Tests.requiredCallbacks.indexOf(wrappedFunction);
if (i >= 0) {
Tests.requiredCallbacks.splice(i, 1); // Delete.
}
return fn.apply(null, arguments);
};
Tests.requiredCallbacks.push(wrappedFunction);
return wrappedFunction;
}
function AssertionError(message) {
this.name = AssertionError;
this.message = message;
}
AssertionError.prototype = new Error();
AssertionError.prototype.constructor = AssertionError;
/*
* A Context is a named set of test methods and nested contexts, with optional setup and teardown
* blocks.
*/
function Context(name) {
this.name = name;
this.setupMethod = null;
this.teardownMethod = null;
this.contexts = [];
this.tests = [];
}
const contextStack = [];
/*
* See the usage documentation for details on how to use the "context" and "should" functions.
*/
function context(name, fn) {
if (typeof fn != "function") {
throw new Error("context() requires a function argument.");
}
const newContext = new Context(name);
if (contextStack.length > 0) {
contextStack[contextStack.length - 1].tests.push(newContext);
} else {
Tests.topLevelContexts.push(newContext);
}
contextStack.push(newContext);
fn();
contextStack.pop();
return newContext;
}
context.only = (name, fn) => {
const c = context(name, fn);
c.isFocused = true;
Tests.focusIsUsed = true;
};
function setup(fn) {
contextStack[contextStack.length - 1].setupMethod = fn;
}
function teardown(fn) {
contextStack[contextStack.length - 1].teardownMethod = fn;
}
function should(name, fn) {
const test = { name, fn };
contextStack[contextStack.length - 1].tests.push(test);
return test;
}
should.only = (name, fn) => {
const test = should(name, fn);
test.isFocused = true;
Tests.focusIsUsed = true;
};
/*
* Tests is used to run tests and keep track of the count of successes and failures.
*/
const Tests = {
topLevelContexts: [],
testsRun: 0,
testsFailed: 0,
// The list of callbacks to ensure are called by the end of the test. This list is appended to by
// `ensureCalled`.
requiredCallbacks: [],
// True if, during the collection phase, should.only or context.only was used.
focusIsUsed: false,
/*
* Run all contexts which have been defined.
* - testNameFilter: a String. If provided, only run tests which match testNameFilter will be run.
*/
run: async function (testNameFilter) {
// Run every top level context (i.e. those not defined within another context). These will in
// turn run any nested contexts. The very last context ever added to Tests.testContexts is a top
// level context. Note that any contexts which have not already been run by a previous top level
// context must themselves be top level contexts.
this.testsRun = 0;
this.testsFailed = 0;
for (const context of this.topLevelContexts) {
await this.runContext(context, [], testNameFilter);
}
this.printTestSummary();
return this.testsFailed == 0;
},
/*
* This resets (clears) the state of shoulda, including the tests which have been defined. This is
* useful when running shoulda tests in a REPL environment, to prevent tests from getting defined
* multiple times when a file is re-evaluated.
*/
reset: function () {
this.topLevelContexts = [];
this.focusedTests = [];
this.focusIsUsed = false;
},
/*
* Run a context. This runs the test methods defined in the context first, and then any nested
* contexts.
*/
runContext: async function (context, parentContexts, testNameFilter) {
parentContexts = parentContexts.concat([context]);
for (const test of context.tests) {
if (test instanceof Context) {
await this.runContext(test, parentContexts, testNameFilter);
} else {
await this.runTest(test, parentContexts, testNameFilter);
}
}
},
/*
* Run a test method. This will run all setup methods in all contexts, and then all teardown
* methods.
* - testMethod: an object with keys name, fn.
* - contexts: an array of Contexts, ordered outer to inner.
* - testNameFilter: A String. If provided, only run the test if it matches testNameFilter.
*/
runTest: async function (testMethod, contexts, testNameFilter) {
if (
this.focusIsUsed && !testMethod.isFocused &&
!contexts.some((c) => c.isFocused)
) {
return;
}
const fullTestName = this.fullyQualifiedName(testMethod.name, contexts);
if (testNameFilter && !fullTestName.includes(testNameFilter)) {
return;
}
this.testsRun++;
let failureMessage = null;
// This is the scope which all references to "this" in the setup and test methods will resolve to.
const testScope = {};
try {
try {
for (const context of contexts) {
if (context.setupMethod) {
await context.setupMethod.call(testScope, testScope);
}
}
await testMethod.fn.call(testScope, testScope);
} finally {
for (const context of contexts) {
if (context.teardownMethod) {
await context.teardownMethod.call(testScope, testScope);
}
}
}
} catch (error) {
// Note that error can be either a String or an Error.
const failedAssertion = error instanceof AssertionError;
failureMessage = failedAssertion ? error.message : error.toString();
if (!failedAssertion && error.stack) {
failureMessage += "\n" + error.stack;
}
}
if (!failureMessage && this.requiredCallbacks.length > 0) {
failureMessage =
"A callback function should have been called during this test, but it wasn't.";
}
if (failureMessage) {
Tests.testsFailed++;
Tests.printFailure(fullTestName, failureMessage);
}
this.requiredCallbacks = [];
clearStubs();
},
// The fully-qualified name of the test or context, e.g. "context1: context2: testName".
fullyQualifiedName: function (testName, contexts) {
return contexts.map((c) => c.name).concat(testName).join(": ");
},
printTestSummary: function () {
if (this.testsFailed > 0) {
console.log(`Fail (${Tests.testsFailed}/${Tests.testsRun})`);
} else {
console.log(`Pass (${Tests.testsRun}/${Tests.testsRun})`);
}
},
printFailure: function (testName, failureMessage) {
console.log(`Fail "${testName}"`, failureMessage);
},
};
function run(testNameFilter) {
return Tests.run(testNameFilter);
}
function reset() {
Tests.reset();
}
/*
* Stats of the latest test run.
*/
function getStats() {
return {
failed: Tests.testsFailed,
run: Tests.testsRun,
};
}
/*
* Stubs
*/
const stubbedObjects = [];
function stub(object, propertyName, returnValue) {
stubbedObjects.push({
object: object,
propertyName: propertyName,
original: object[propertyName],
});
object[propertyName] = returnValue;
}
/*
* returns creates a function which returns the given value. This is useful for stubbing functions
* to return a hardcoded value.
*/
function returns(value) {
return () => value;
}
function clearStubs() {
// Restore stubs in the reverse order they were defined in, in case the same property was stubbed
// twice.
for (let i = stubbedObjects.length - 1; i >= 0; i--) {
const stubProperties = stubbedObjects[i];
stubProperties.object[stubProperties.propertyName] =
stubProperties.original;
}
}
export {
assert,
context,
ensureCalled,
getStats,
reset,
returns,
run,
setup,
should,
stub,
teardown,
};