-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
assert.js
406 lines (360 loc) · 10.2 KB
/
assert.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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
'use strict';
const coreAssert = require('core-assert');
const deepEqual = require('lodash.isequal');
const observableToPromise = require('observable-to-promise');
const indentString = require('indent-string');
const isObservable = require('is-observable');
const isPromise = require('is-promise');
const jestSnapshot = require('jest-snapshot');
const enhanceAssert = require('./enhance-assert');
const formatAssertError = require('./format-assert-error');
const snapshotState = require('./snapshot-state');
class AssertionError extends Error {
constructor(opts) {
super(opts.message || '');
this.name = 'AssertionError';
this.assertion = opts.assertion;
this.operator = opts.operator;
this.values = opts.values || [];
// Reserved for power-assert statements
this.statements = [];
if (opts.stack) {
this.stack = opts.stack;
}
}
}
exports.AssertionError = AssertionError;
function wrapAssertions(callbacks) {
const pass = callbacks.pass;
const pending = callbacks.pending;
const fail = callbacks.fail;
const noop = () => {};
const makeNoop = () => noop;
const makeRethrow = reason => () => {
throw reason;
};
const assertions = {
pass() {
pass(this);
},
fail(message) {
fail(this, new AssertionError({
assertion: 'fail',
message: message || 'Test failed via `t.fail()`'
}));
},
is(actual, expected, message) {
if (actual === expected) {
pass(this);
} else {
const diff = formatAssertError.formatDiff(actual, expected);
const values = diff ? [diff] : [
formatAssertError.formatWithLabel('Actual:', actual),
formatAssertError.formatWithLabel('Must be strictly equal to:', expected)
];
fail(this, new AssertionError({
assertion: 'is',
message,
operator: '===',
values
}));
}
},
not(actual, expected, message) {
if (actual === expected) {
fail(this, new AssertionError({
assertion: 'not',
message,
operator: '!==',
values: [formatAssertError.formatWithLabel('Value is strictly equal:', actual)]
}));
} else {
pass(this);
}
},
deepEqual(actual, expected, message) {
if (deepEqual(actual, expected)) {
pass(this);
} else {
const diff = formatAssertError.formatDiff(actual, expected);
const values = diff ? [diff] : [
formatAssertError.formatWithLabel('Actual:', actual),
formatAssertError.formatWithLabel('Must be deeply equal to:', expected)
];
fail(this, new AssertionError({
assertion: 'deepEqual',
message,
values
}));
}
},
notDeepEqual(actual, expected, message) {
if (deepEqual(actual, expected)) {
fail(this, new AssertionError({
assertion: 'notDeepEqual',
message,
values: [formatAssertError.formatWithLabel('Value is deeply equal:', actual)]
}));
} else {
pass(this);
}
},
throws(fn, err, message) {
let promise;
if (isPromise(fn)) {
promise = fn;
} else if (isObservable(fn)) {
promise = observableToPromise(fn);
} else if (typeof fn !== 'function') {
fail(this, new AssertionError({
assertion: 'throws',
message: '`t.throws()` must be called with a function, Promise, or Observable',
values: [formatAssertError.formatWithLabel('Called with:', fn)]
}));
return;
}
let coreAssertThrowsErrorArg;
if (typeof err === 'string') {
const expectedMessage = err;
coreAssertThrowsErrorArg = error => error.message === expectedMessage;
} else {
// Assume it's a constructor function or regular expression
coreAssertThrowsErrorArg = err;
}
const test = fn => {
let actual;
let threw = false;
try {
coreAssert.throws(() => {
try {
fn();
} catch (err) {
actual = err;
threw = true;
throw err;
}
}, coreAssertThrowsErrorArg);
return actual;
} catch (err) {
const values = threw ?
[formatAssertError.formatWithLabel('Threw unexpected exception:', actual)] :
null;
throw new AssertionError({
assertion: 'throws',
message,
values
});
}
};
if (promise) {
const result = promise.then(makeNoop, makeRethrow).then(test);
pending(this, result);
return result;
}
try {
const retval = test(fn);
pass(this);
return retval;
} catch (err) {
fail(this, err);
}
},
notThrows(fn, message) {
let promise;
if (isPromise(fn)) {
promise = fn;
} else if (isObservable(fn)) {
promise = observableToPromise(fn);
} else if (typeof fn !== 'function') {
fail(this, new AssertionError({
assertion: 'notThrows',
message: '`t.notThrows()` must be called with a function, Promise, or Observable',
values: [formatAssertError.formatWithLabel('Called with:', fn)]
}));
return;
}
const test = fn => {
try {
coreAssert.doesNotThrow(fn);
} catch (err) {
throw new AssertionError({
assertion: 'notThrows',
message,
values: [formatAssertError.formatWithLabel('Threw:', err.actual)]
});
}
};
if (promise) {
const result = promise
.then(noop, reason => test(makeRethrow(reason)));
pending(this, result);
return result;
}
try {
test(fn);
pass(this);
} catch (err) {
fail(this, err);
}
},
ifError(actual, message) {
if (actual) {
fail(this, new AssertionError({
assertion: 'ifError',
message,
values: [formatAssertError.formatWithLabel('Error:', actual)]
}));
} else {
pass(this);
}
},
snapshot(actual, optionalMessage) {
const result = snapshot(this, actual, optionalMessage);
if (result.pass) {
pass(this);
} else {
const diff = formatAssertError.formatDiff(actual, result.expected);
const values = diff ? [diff] : [
formatAssertError.formatWithLabel('Actual:', actual),
formatAssertError.formatWithLabel('Must be deeply equal to:', result.expected)
];
fail(this, new AssertionError({
assertion: 'snapshot',
message: result.message,
values
}));
}
}
};
const enhancedAssertions = enhanceAssert(pass, fail, {
truthy(actual, message) {
if (!actual) {
throw new AssertionError({
assertion: 'truthy',
message,
operator: '!!',
values: [formatAssertError.formatWithLabel('Value is not truthy:', actual)]
});
}
},
falsy(actual, message) {
if (actual) {
throw new AssertionError({
assertion: 'falsy',
message,
operator: '!',
values: [formatAssertError.formatWithLabel('Value is not falsy:', actual)]
});
}
},
true(actual, message) {
if (actual !== true) {
throw new AssertionError({
assertion: 'true',
message,
values: [formatAssertError.formatWithLabel('Value is not `true`:', actual)]
});
}
},
false(actual, message) {
if (actual !== false) {
throw new AssertionError({
assertion: 'false',
message,
values: [formatAssertError.formatWithLabel('Value is not `false`:', actual)]
});
}
},
regex(string, regex, message) {
if (typeof string !== 'string') {
throw new AssertionError({
assertion: 'regex',
message: '`t.regex()` must be called with a string',
values: [formatAssertError.formatWithLabel('Called with:', string)]
});
}
if (!(regex instanceof RegExp)) {
throw new AssertionError({
assertion: 'regex',
message: '`t.regex()` must be called with a regular expression',
values: [formatAssertError.formatWithLabel('Called with:', regex)]
});
}
if (!regex.test(string)) {
throw new AssertionError({
assertion: 'regex',
message,
values: [
formatAssertError.formatWithLabel('Value must match expression:', string),
formatAssertError.formatWithLabel('Regular expression:', regex)
]
});
}
},
notRegex(string, regex, message) {
if (typeof string !== 'string') {
throw new AssertionError({
assertion: 'notRegex',
message: '`t.notRegex()` must be called with a string',
values: [formatAssertError.formatWithLabel('Called with:', string)]
});
}
if (!(regex instanceof RegExp)) {
throw new AssertionError({
assertion: 'notRegex',
message: '`t.notRegex()` must be called with a regular expression',
values: [formatAssertError.formatWithLabel('Called with:', regex)]
});
}
if (regex.test(string)) {
throw new AssertionError({
assertion: 'notRegex',
message,
values: [
formatAssertError.formatWithLabel('Value must not match expression:', string),
formatAssertError.formatWithLabel('Regular expression:', regex)
]
});
}
}
});
return Object.assign(assertions, enhancedAssertions);
}
exports.wrapAssertions = wrapAssertions;
function snapshot(executionContext, tree, optionalMessage, match, snapshotStateGetter) {
// Set defaults - this allows tests to mock deps easily
const toMatchSnapshot = match || jestSnapshot.toMatchSnapshot;
const getState = snapshotStateGetter || snapshotState.get;
const state = getState();
const context = {
dontThrow() {},
currentTestName: executionContext.title,
snapshotState: state
};
// Symbols can't be serialized and saved in a snapshot, that's why tree
// is saved in the `__ava_react_jsx` prop, so that JSX can be detected later
const serializedTree = tree.$$typeof === Symbol.for('react.test.json') ? {__ava_react_jsx: tree} : tree; // eslint-disable-line camelcase
const result = toMatchSnapshot.call(context, JSON.stringify(serializedTree));
let message = 'Please check your code or --update-snapshots';
if (optionalMessage) {
message += '\n\n' + indentString(optionalMessage, 2);
}
state.save();
let expected;
if (result.expected) {
// JSON in a snapshot is surrounded with `"`, because jest-snapshot
// serializes snapshot values too, so it ends up double JSON encoded
expected = JSON.parse(result.expected.slice(1).slice(0, -1));
// Define a `$$typeof` symbol, so that pretty-format detects it as React tree
if (expected.__ava_react_jsx) { // eslint-disable-line camelcase
expected = expected.__ava_react_jsx; // eslint-disable-line camelcase
Object.defineProperty(expected, '$$typeof', {value: Symbol.for('react.test.json')});
}
}
return {
pass: result.pass,
expected,
message
};
}
exports.snapshot = snapshot;