@provino/expect 0.0.0-stage → 0.1.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +8 -2
- package/dist/index.d.ts +322 -0
- package/dist/index.js +1333 -0
- package/package.json +41 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,1333 @@
|
|
|
1
|
+
import { equals } from "@jest/expect-utils";
|
|
2
|
+
import { types } from "node:util";
|
|
3
|
+
import { dirname, resolve } from "node:path";
|
|
4
|
+
import { SnapshotError, SnapshotState, deepMerge, unwrapMatcherSnapshotState } from "@provino/snapshot/runtime";
|
|
5
|
+
|
|
6
|
+
// src/internal/counters.ts
|
|
7
|
+
/**
|
|
8
|
+
* Fresh counters: a new state's, and the asymmetric base's when no slot is installed.
|
|
9
|
+
* @internal
|
|
10
|
+
*/
|
|
11
|
+
function freshCounters() {
|
|
12
|
+
return {
|
|
13
|
+
assertionCalls: 0,
|
|
14
|
+
expectedAssertionsNumber: null,
|
|
15
|
+
isExpectingAssertions: false,
|
|
16
|
+
numPassingAsserts: 0,
|
|
17
|
+
pendingAsync: /* @__PURE__ */ new Set(),
|
|
18
|
+
suppressedErrors: []
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
/** The state's counters a test's end resets, from `freshCounters()`'s own keys: written once. */
|
|
22
|
+
const FRESH = freshCounters();
|
|
23
|
+
const COUNTER_KEYS = Object.keys(FRESH).filter((key) => key !== "pendingAsync");
|
|
24
|
+
/**
|
|
25
|
+
* Whether `state` holds anything an assertion outside a test left: a call, a pass, an expected
|
|
26
|
+
* count, an `expect.hasAssertions()` or a held-back failure.
|
|
27
|
+
* @internal
|
|
28
|
+
*/
|
|
29
|
+
function hasCounts(state) {
|
|
30
|
+
for (const key of COUNTER_KEYS) {
|
|
31
|
+
const value = state[key];
|
|
32
|
+
if (Array.isArray(value) ? value.length > 0 : value !== FRESH[key]) return true;
|
|
33
|
+
}
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Moves the counters Jest's `extractExpectedAssertionsErrors` and `_addSuppressedErrors` reset from
|
|
38
|
+
* `from` to `to`, and leaves `from` fresh. Jest's one state is reset only when a test ends, so what
|
|
39
|
+
* was counted before reaches the next test that ends (`ExpectPolicy.outsideTestCounts:
|
|
40
|
+
* 'next-test'`). The expectation errors travel with their counts.
|
|
41
|
+
* @internal
|
|
42
|
+
*/
|
|
43
|
+
function moveCounters(from, to) {
|
|
44
|
+
const fresh = freshCounters();
|
|
45
|
+
for (const key of COUNTER_KEYS) {
|
|
46
|
+
to[key] = from[key];
|
|
47
|
+
from[key] = fresh[key];
|
|
48
|
+
}
|
|
49
|
+
for (const key of ERROR_KEYS) {
|
|
50
|
+
if (from[key] === void 0) delete to[key];
|
|
51
|
+
else to[key] = from[key];
|
|
52
|
+
delete from[key];
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** The errors made beside `expectedAssertionsNumber` and `isExpectingAssertions`. */
|
|
56
|
+
const ERROR_KEYS = ["expectedAssertionsNumberError", "isExpectingAssertionsError"];
|
|
57
|
+
|
|
58
|
+
// src/errors.ts
|
|
59
|
+
/**
|
|
60
|
+
* An error from the engine itself, never from an assertion.
|
|
61
|
+
* @public
|
|
62
|
+
*/
|
|
63
|
+
var ExpectError = class extends Error {
|
|
64
|
+
code;
|
|
65
|
+
constructor(code, message) {
|
|
66
|
+
super(message);
|
|
67
|
+
this.name = "ExpectError";
|
|
68
|
+
this.code = code;
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
// src/internal/own-properties.ts
|
|
73
|
+
/**
|
|
74
|
+
* Remembers every own property of `target` (string and symbol keys) with its descriptor, and
|
|
75
|
+
* returns the function that puts `target` back: keys added since are deleted, and any key that is
|
|
76
|
+
* gone or changed is defined again from its saved descriptor. The object stays the same one.
|
|
77
|
+
* A key that can't be deleted or redefined (non-configurable) is left, as `Reflect` reports it.
|
|
78
|
+
* @internal
|
|
79
|
+
*/
|
|
80
|
+
function snapshotOwnProperties(target) {
|
|
81
|
+
const saved = /* @__PURE__ */ new Map();
|
|
82
|
+
for (const key of Reflect.ownKeys(target)) {
|
|
83
|
+
const descriptor = Reflect.getOwnPropertyDescriptor(target, key);
|
|
84
|
+
if (descriptor !== void 0) saved.set(key, descriptor);
|
|
85
|
+
}
|
|
86
|
+
return () => {
|
|
87
|
+
for (const key of Reflect.ownKeys(target)) if (!saved.has(key)) Reflect.deleteProperty(target, key);
|
|
88
|
+
for (const [key, descriptor] of saved) {
|
|
89
|
+
const now = Reflect.getOwnPropertyDescriptor(target, key);
|
|
90
|
+
if (now === void 0 || differs(now, descriptor)) Reflect.defineProperty(target, key, descriptor);
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
/** Whether two descriptors of one key differ in a value, an accessor or a flag. */
|
|
95
|
+
function differs(a, b) {
|
|
96
|
+
return !Object.is(a.value, b.value) || a.get !== b.get || a.set !== b.set || a.writable !== b.writable || a.enumerable !== b.enumerable || a.configurable !== b.configurable;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// src/slot.ts
|
|
100
|
+
/**
|
|
101
|
+
* The slot's key. Both runners use it (Track 7 F3).
|
|
102
|
+
* @public
|
|
103
|
+
*/
|
|
104
|
+
const MATCHERS_SLOT = Symbol.for("$$jest-matchers-object");
|
|
105
|
+
/**
|
|
106
|
+
* An empty registry, made before the slot so the slot exists before any matcher module loads.
|
|
107
|
+
* @public
|
|
108
|
+
*/
|
|
109
|
+
function createMatcherRegistry() {
|
|
110
|
+
return {
|
|
111
|
+
matchers: Object.create(null),
|
|
112
|
+
customEqualityTesters: [],
|
|
113
|
+
utils: {}
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Remembers what `registry` holds now, and, when `expect` is given, the own properties of `expect`
|
|
118
|
+
* and of `expect.not`. The worker takes one after `createExpect` has registered the dialect's
|
|
119
|
+
* matchers (an earlier one would restore them away), and restores it after each file when the
|
|
120
|
+
* environment is file-scoped, as Jest gives each file a fresh `expect`.
|
|
121
|
+
*
|
|
122
|
+
* `expect.extend` puts a custom matcher's asymmetric form (`expect.toBeEven()`) on `expect` and on
|
|
123
|
+
* `expect.not`, outside the registry; pass `expect` so those are undone too.
|
|
124
|
+
* @beta
|
|
125
|
+
*/
|
|
126
|
+
function snapshotRegistry(registry, expect) {
|
|
127
|
+
const restoreMatchers = snapshotOwnProperties(registry.matchers);
|
|
128
|
+
const restoreStatics = [];
|
|
129
|
+
if (expect !== void 0) {
|
|
130
|
+
restoreStatics.push(snapshotOwnProperties(expect));
|
|
131
|
+
const not = Reflect.get(expect, "not");
|
|
132
|
+
if (typeof not === "object" && not !== null) restoreStatics.push(snapshotOwnProperties(not));
|
|
133
|
+
}
|
|
134
|
+
const testers = [...registry.customEqualityTesters];
|
|
135
|
+
return { restore() {
|
|
136
|
+
restoreMatchers();
|
|
137
|
+
for (const restore of restoreStatics) restore();
|
|
138
|
+
registry.customEqualityTesters.length = 0;
|
|
139
|
+
registry.customEqualityTesters.push(...testers);
|
|
140
|
+
} };
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Installs the slot on `globalThis`. Throws `EXPECT_SLOT_TAKEN` if another one is there: a
|
|
144
|
+
* non-configurable one means Jest's `expect` loaded first in this realm, which the worker must
|
|
145
|
+
* prevent (the slot comes before any matcher module).
|
|
146
|
+
* @public
|
|
147
|
+
*/
|
|
148
|
+
function installMatchersSlot(source, registry) {
|
|
149
|
+
if (Object.hasOwn(globalThis, MATCHERS_SLOT)) throw new ExpectError("EXPECT_SLOT_TAKEN", "globalThis[Symbol.for(\"$$jest-matchers-object\")] is already defined: install the slot before any expect or matcher module loads");
|
|
150
|
+
const slot = {
|
|
151
|
+
matchers: registry.matchers,
|
|
152
|
+
customEqualityTesters: registry.customEqualityTesters,
|
|
153
|
+
get state() {
|
|
154
|
+
return source.current();
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
Object.defineProperty(slot, "utils", { get: () => registry.utils });
|
|
158
|
+
Object.defineProperty(globalThis, MATCHERS_SLOT, {
|
|
159
|
+
value: slot,
|
|
160
|
+
configurable: true
|
|
161
|
+
});
|
|
162
|
+
return { uninstall() {
|
|
163
|
+
if (Reflect.get(globalThis, MATCHERS_SLOT) === slot) Reflect.deleteProperty(globalThis, MATCHERS_SLOT);
|
|
164
|
+
} };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// src/internal/slot-read.ts
|
|
168
|
+
/**
|
|
169
|
+
* The slot in this realm, whoever installed it; any field may be missing (Jest's has no `utils`).
|
|
170
|
+
* @internal
|
|
171
|
+
*/
|
|
172
|
+
function readSlot() {
|
|
173
|
+
const slot = Reflect.get(globalThis, MATCHERS_SLOT);
|
|
174
|
+
return typeof slot === "object" && slot !== null ? slot : {};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// src/asymmetric.ts
|
|
178
|
+
/**
|
|
179
|
+
* The base every asymmetric matcher extends.
|
|
180
|
+
* @public
|
|
181
|
+
*/
|
|
182
|
+
var AsymmetricMatcher = class {
|
|
183
|
+
$$typeof = Symbol.for("jest.asymmetricMatcher");
|
|
184
|
+
sample;
|
|
185
|
+
inverse;
|
|
186
|
+
constructor(sample, inverse = false) {
|
|
187
|
+
this.sample = sample;
|
|
188
|
+
this.inverse = inverse;
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* A matcher context like the one a matcher gets (Jest's `getMatcherContext`): the current
|
|
192
|
+
* state, the realm's equality testers and `utils`, and `isNot` from `inverse`. It reads the
|
|
193
|
+
* slot, so it works under whichever engine installed it.
|
|
194
|
+
*/
|
|
195
|
+
getMatcherContext() {
|
|
196
|
+
const slot = readSlot();
|
|
197
|
+
return {
|
|
198
|
+
customTesters: slot.customEqualityTesters ?? [],
|
|
199
|
+
dontThrow: () => {},
|
|
200
|
+
...slot.state ?? EMPTY_STATE,
|
|
201
|
+
equals,
|
|
202
|
+
isNot: this.inverse,
|
|
203
|
+
utils: slot.utils ?? {}
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
/** The state outside any engine: no slot in this realm. */
|
|
208
|
+
const EMPTY_STATE = freshCounters();
|
|
209
|
+
|
|
210
|
+
// src/call-stack.ts
|
|
211
|
+
/**
|
|
212
|
+
* The engine's frames around a matcher: `throwingMatcher` calls every matcher
|
|
213
|
+
* (`makeThrowingMatcher` in `expect.ts`), and a custom one runs inside
|
|
214
|
+
* `__EXTERNAL_MATCHER_TRAP__`, Jest's name, which jest-snapshot cuts its stack at.
|
|
215
|
+
*/
|
|
216
|
+
const ENGINE_FRAME = /\b(?:throwingMatcher|__EXTERNAL_MATCHER_TRAP__)\b/;
|
|
217
|
+
/** Enough frames to reach the user's call through two nested custom matchers and the state. */
|
|
218
|
+
const CALL_STACK_LIMIT = 50;
|
|
219
|
+
/**
|
|
220
|
+
* The stack of a matcher's call, its first frame the user's call, taken when the thunk runs (the
|
|
221
|
+
* state calls it only when it writes an inline snapshot, inside the same `match` call). Under
|
|
222
|
+
* `.resolves`/`.rejects` it is the error the engine made at the call (Jest's `context.error`).
|
|
223
|
+
* Otherwise it is Jest's rule (State.ts `_addSnapshot`, utils.ts
|
|
224
|
+
* `removeLinesBeforeExternalMatcherTrap`): the lines after the innermost matcher call, past the
|
|
225
|
+
* engine's frames, which Jest's `getTopFrame` passes over in `node_modules` and which, run from
|
|
226
|
+
* source, are outside it here. Jest registers its own snapshot matchers with `expect.extend`, so
|
|
227
|
+
* they run inside a trap as a custom one does; Provino's are built-ins with no trap, so for them
|
|
228
|
+
* the innermost call is the engine's `throwingMatcher`. Either way a matcher called through
|
|
229
|
+
* `expect` inside a custom matcher writes into that matcher's body
|
|
230
|
+
* (`ecosystem/custom-snapshot-inline-nested`).
|
|
231
|
+
* @public
|
|
232
|
+
*/
|
|
233
|
+
function matcherCallStack(error) {
|
|
234
|
+
const stack = () => {
|
|
235
|
+
if (error?.stack !== void 0) return error.stack;
|
|
236
|
+
const holder = {};
|
|
237
|
+
const limit = Error.stackTraceLimit;
|
|
238
|
+
Error.stackTraceLimit = Math.max(limit, CALL_STACK_LIMIT);
|
|
239
|
+
try {
|
|
240
|
+
Error.captureStackTrace(holder, stack);
|
|
241
|
+
} finally {
|
|
242
|
+
Error.stackTraceLimit = limit;
|
|
243
|
+
}
|
|
244
|
+
const lines = (holder.stack ?? "").split("\n");
|
|
245
|
+
const cut = lines.findIndex((line) => ENGINE_FRAME.test(line));
|
|
246
|
+
if (cut === -1) return lines.join("\n");
|
|
247
|
+
let at = cut + 1;
|
|
248
|
+
while (at < lines.length && ENGINE_FRAME.test(lines[at] ?? "")) at++;
|
|
249
|
+
return lines.slice(at).join("\n");
|
|
250
|
+
};
|
|
251
|
+
return stack;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// src/end-of-test.ts
|
|
255
|
+
/**
|
|
256
|
+
* Builds the end-of-test check.
|
|
257
|
+
* @public
|
|
258
|
+
*/
|
|
259
|
+
function createEndOfTest(options) {
|
|
260
|
+
const { source, messages, hasAssertionsWhenFailed } = options;
|
|
261
|
+
const { requireAssertions } = options.policy;
|
|
262
|
+
return function endOfTest(attempt) {
|
|
263
|
+
const state = source.settle(attempt.test.id, attempt);
|
|
264
|
+
if (state === void 0) return requireAssertions && !(attempt.failed && hasAssertionsWhenFailed === "skip") ? [new Error(messages.requiredAssertions())] : [];
|
|
265
|
+
const errors = takeSuppressed(state);
|
|
266
|
+
const failed = attempt.failed || errors.length > 0;
|
|
267
|
+
errors.push(...countErrors(state, failed));
|
|
268
|
+
errors.push(...takeUnawaited(state));
|
|
269
|
+
return errors;
|
|
270
|
+
};
|
|
271
|
+
/** The failures held back, which are the attempt's now. */
|
|
272
|
+
function takeSuppressed(state) {
|
|
273
|
+
const held = state.suppressedErrors;
|
|
274
|
+
state.suppressedErrors = [];
|
|
275
|
+
return held;
|
|
276
|
+
}
|
|
277
|
+
/** Jest's `_addExpectedAssertionErrors`, plus `requireAssertions`. */
|
|
278
|
+
function countErrors(state, failed) {
|
|
279
|
+
const { assertionCalls, expectedAssertionsNumber, isExpectingAssertions } = state;
|
|
280
|
+
const errors = [];
|
|
281
|
+
if (typeof expectedAssertionsNumber === "number" && assertionCalls !== expectedAssertionsNumber) {
|
|
282
|
+
const error = state.expectedAssertionsNumberError ?? /* @__PURE__ */ new Error();
|
|
283
|
+
error.message = messages.assertionCount(expectedAssertionsNumber, assertionCalls);
|
|
284
|
+
errors.push(error);
|
|
285
|
+
}
|
|
286
|
+
if (isExpectingAssertions && assertionCalls === 0) {
|
|
287
|
+
const error = state.isExpectingAssertionsError ?? /* @__PURE__ */ new Error();
|
|
288
|
+
error.message = messages.noAssertions();
|
|
289
|
+
errors.push(error);
|
|
290
|
+
}
|
|
291
|
+
const skipped = failed && hasAssertionsWhenFailed === "skip";
|
|
292
|
+
if (skipped && isExpectingAssertions) return [];
|
|
293
|
+
if (requireAssertions && assertionCalls === 0 && !isExpectingAssertions && !skipped) errors.push(new Error(messages.requiredAssertions()));
|
|
294
|
+
return errors;
|
|
295
|
+
}
|
|
296
|
+
/** The async assertions nobody awaited, worded by the table, each with the stack of its call. */
|
|
297
|
+
function takeUnawaited(state) {
|
|
298
|
+
const errors = [];
|
|
299
|
+
for (const pending of state.pendingAsync) {
|
|
300
|
+
pending.error.message = messages.unawaited(pending);
|
|
301
|
+
errors.push(pending.error);
|
|
302
|
+
}
|
|
303
|
+
state.pendingAsync.clear();
|
|
304
|
+
return errors;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// src/equality.ts
|
|
309
|
+
const classTag = Object.prototype.toString;
|
|
310
|
+
/** `Error.isError` where Node has it, else the class tag (which a subclass of `Error` has too). */
|
|
311
|
+
function isError$1(value) {
|
|
312
|
+
const native = Error.isError;
|
|
313
|
+
if (typeof native === "function") return native(value);
|
|
314
|
+
switch (classTag.call(value)) {
|
|
315
|
+
case "[object Error]":
|
|
316
|
+
case "[object Exception]":
|
|
317
|
+
case "[object DOMException]": return true;
|
|
318
|
+
default: return false;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
const isDate = (value) => classTag.call(value) === "[object Date]";
|
|
322
|
+
/**
|
|
323
|
+
* `invalidDate: 'equal'`: two dates that are both invalid (`NaN` milliseconds) are equal. Any
|
|
324
|
+
* other pair is Jest's `equals` to judge.
|
|
325
|
+
*/
|
|
326
|
+
const invalidDatesAreEqual = (a, b) => isDate(a) && isDate(b) && Number.isNaN(+a) && Number.isNaN(+b) ? true : void 0;
|
|
327
|
+
/** The pairs of errors being compared now (Vitest's `aStack` and `bStack`), so an error that is its own cause ends the walk. */
|
|
328
|
+
const comparing = [];
|
|
329
|
+
/**
|
|
330
|
+
* `errors: 'assert'`: two errors are equal as `node:assert` has it: the same class, name and
|
|
331
|
+
* message, the same `cause` when the expected one has one, the same `errors` for an
|
|
332
|
+
* `AggregateError`, and the same own enumerable properties. Jest's `equals` compares only the
|
|
333
|
+
* message.
|
|
334
|
+
*/
|
|
335
|
+
const errorsLikeAssert = function(a, b, customTesters) {
|
|
336
|
+
if (!isError$1(a) || !isError$1(b)) return void 0;
|
|
337
|
+
for (let i = comparing.length - 1; i >= 0; i--) {
|
|
338
|
+
const pair = comparing[i];
|
|
339
|
+
if (pair === void 0) continue;
|
|
340
|
+
if (pair[0] === a) return pair[1] === b;
|
|
341
|
+
if (pair[1] === b) return false;
|
|
342
|
+
}
|
|
343
|
+
comparing.push([a, b]);
|
|
344
|
+
try {
|
|
345
|
+
if (!(classTag.call(a) === classTag.call(b) && a.name === b.name && a.message === b.message)) return false;
|
|
346
|
+
if (typeof b.cause !== "undefined" && !this.equals(a.cause, b.cause, customTesters)) return false;
|
|
347
|
+
const aErrors = Reflect.get(a, "errors");
|
|
348
|
+
const bErrors = Reflect.get(b, "errors");
|
|
349
|
+
if (a.name === "AggregateError" && b.name === "AggregateError" && Array.isArray(aErrors) && Array.isArray(bErrors) && !this.equals(aErrors, bErrors, customTesters)) return false;
|
|
350
|
+
return this.equals({ ...a }, { ...b }, customTesters);
|
|
351
|
+
} finally {
|
|
352
|
+
comparing.pop();
|
|
353
|
+
}
|
|
354
|
+
};
|
|
355
|
+
/**
|
|
356
|
+
* The testers an `ExpectPolicy.equality` asks for, in the order they go ahead of the others.
|
|
357
|
+
* Jest's values ask for none.
|
|
358
|
+
* @public
|
|
359
|
+
*/
|
|
360
|
+
function equalityTesters(equality) {
|
|
361
|
+
return [...equality.errors === "assert" ? [errorsLikeAssert] : [], ...equality.invalidDate === "equal" ? [invalidDatesAreEqual] : []];
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// src/internal/awaitable.ts
|
|
365
|
+
/**
|
|
366
|
+
* A thenable over `source()` that calls `onAwaited` the first time anyone takes its result with
|
|
367
|
+
* `then`, `catch` or `finally`. `source` is asked on each call, so a caller that wants a lazy
|
|
368
|
+
* start memoizes it.
|
|
369
|
+
* @internal
|
|
370
|
+
*/
|
|
371
|
+
function awaitable(source, onAwaited) {
|
|
372
|
+
return {
|
|
373
|
+
then(onFulfilled, onRejected) {
|
|
374
|
+
onAwaited();
|
|
375
|
+
return source().then(onFulfilled, onRejected);
|
|
376
|
+
},
|
|
377
|
+
catch(onRejected) {
|
|
378
|
+
onAwaited();
|
|
379
|
+
return source().catch(onRejected);
|
|
380
|
+
},
|
|
381
|
+
finally(onFinally) {
|
|
382
|
+
onAwaited();
|
|
383
|
+
return source().finally(onFinally);
|
|
384
|
+
},
|
|
385
|
+
[Symbol.toStringTag]: "Promise"
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// src/poll.ts
|
|
390
|
+
/** Matchers that cannot work with a poll: they would never pass, or they snapshot. */
|
|
391
|
+
const UNSUPPORTED = /* @__PURE__ */ new Set([
|
|
392
|
+
"resolves",
|
|
393
|
+
"rejects",
|
|
394
|
+
"toMatchSnapshot",
|
|
395
|
+
"toMatchInlineSnapshot",
|
|
396
|
+
"toThrowErrorMatchingSnapshot",
|
|
397
|
+
"toThrowErrorMatchingInlineSnapshot",
|
|
398
|
+
"toThrow",
|
|
399
|
+
"toThrowError"
|
|
400
|
+
]);
|
|
401
|
+
/** `promise`'s outcome, or `{ ok: false }` once `timedOut` settles first. */
|
|
402
|
+
function raceWith(promise, timedOut) {
|
|
403
|
+
return Promise.race([promise.then((value) => ({
|
|
404
|
+
ok: true,
|
|
405
|
+
value
|
|
406
|
+
})), timedOut.then(() => ({ ok: false }))]);
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* Gives `error` the stack of `site` (where the user called the matcher), under its own header,
|
|
410
|
+
* as Vitest's `copyStackTrace` does. Anything that isn't an `Error` is returned as it is.
|
|
411
|
+
*/
|
|
412
|
+
function restack(error, site) {
|
|
413
|
+
if (!(error instanceof Error) || typeof site.stack !== "string") return error;
|
|
414
|
+
const frames = site.stack.split("\n").filter((line) => /^\s+at /.test(line));
|
|
415
|
+
error.stack = `${error.name}: ${error.message}\n${frames.join("\n")}`;
|
|
416
|
+
return error;
|
|
417
|
+
}
|
|
418
|
+
/** A time in milliseconds that `setTimeout` accepts. */
|
|
419
|
+
function isTime(value) {
|
|
420
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* Builds `expect.poll` for one engine.
|
|
424
|
+
* @internal
|
|
425
|
+
*/
|
|
426
|
+
function createPoll(engine) {
|
|
427
|
+
const { policy, messages, timers } = engine;
|
|
428
|
+
const realSetTimeout = globalThis.setTimeout;
|
|
429
|
+
const realClearTimeout = globalThis.clearTimeout;
|
|
430
|
+
const setTimer = timers?.setTimeout ?? ((callback, ms) => realSetTimeout(callback, ms));
|
|
431
|
+
const clearTimer = timers?.clearTimeout ?? ((handle) => {
|
|
432
|
+
realClearTimeout(handle);
|
|
433
|
+
});
|
|
434
|
+
/** A wait of `ms`, and a way to cancel its timer. */
|
|
435
|
+
const wait = (ms) => {
|
|
436
|
+
let handle;
|
|
437
|
+
return {
|
|
438
|
+
done: new Promise((resolve) => {
|
|
439
|
+
handle = setTimer(resolve, ms);
|
|
440
|
+
}),
|
|
441
|
+
cancel: () => clearTimer(handle)
|
|
442
|
+
};
|
|
443
|
+
};
|
|
444
|
+
/** One poll: `fn` and the matcher, again and again, until the matcher passes or time is up. */
|
|
445
|
+
async function run(fn, interval, timeout, name, isNot, args, state, site) {
|
|
446
|
+
const controller = new AbortController();
|
|
447
|
+
const total = wait(timeout);
|
|
448
|
+
const timedOut = total.done.then(() => {
|
|
449
|
+
controller.abort();
|
|
450
|
+
});
|
|
451
|
+
let lastError;
|
|
452
|
+
let failed = false;
|
|
453
|
+
try {
|
|
454
|
+
for (;;) try {
|
|
455
|
+
const read = await raceWith(Promise.resolve().then(() => fn({ signal: controller.signal })), timedOut);
|
|
456
|
+
if (!read.ok) {
|
|
457
|
+
if (!failed) lastError = new Error(messages.pollTimeout("function"));
|
|
458
|
+
failed = true;
|
|
459
|
+
break;
|
|
460
|
+
}
|
|
461
|
+
if (!(await raceWith(Promise.resolve().then(() => {
|
|
462
|
+
const before = state.assertionCalls;
|
|
463
|
+
try {
|
|
464
|
+
return engine.run(name, isNot, read.value, args, state);
|
|
465
|
+
} catch (error) {
|
|
466
|
+
state.assertionCalls = before;
|
|
467
|
+
throw error;
|
|
468
|
+
}
|
|
469
|
+
}), timedOut)).ok) {
|
|
470
|
+
if (!failed) lastError = new Error(messages.pollTimeout("assertion"));
|
|
471
|
+
failed = true;
|
|
472
|
+
break;
|
|
473
|
+
}
|
|
474
|
+
return;
|
|
475
|
+
} catch (error) {
|
|
476
|
+
lastError = error;
|
|
477
|
+
failed = true;
|
|
478
|
+
const nap = wait(interval);
|
|
479
|
+
if (!(await raceWith(nap.done, timedOut)).ok) {
|
|
480
|
+
nap.cancel();
|
|
481
|
+
break;
|
|
482
|
+
}
|
|
483
|
+
await timers?.advance?.(interval);
|
|
484
|
+
}
|
|
485
|
+
} finally {
|
|
486
|
+
total.cancel();
|
|
487
|
+
}
|
|
488
|
+
if (policy.pollFailsOnTimeout && failed) throw restack(lastError, site);
|
|
489
|
+
}
|
|
490
|
+
/** The matcher a poll's proxy hands out for `name`. */
|
|
491
|
+
const chain = (fn, interval, timeout, name, isNot) => function pollMatcher(...args) {
|
|
492
|
+
const site = engine.capture(pollMatcher);
|
|
493
|
+
const state = engine.state();
|
|
494
|
+
const call = {
|
|
495
|
+
matcherName: name,
|
|
496
|
+
isNot,
|
|
497
|
+
promise: ""
|
|
498
|
+
};
|
|
499
|
+
let started;
|
|
500
|
+
const start = () => started ??= run(fn, interval, timeout, name, isNot, args, state, site);
|
|
501
|
+
if (!engine.track) return start();
|
|
502
|
+
const pending = {
|
|
503
|
+
kind: "poll",
|
|
504
|
+
call,
|
|
505
|
+
error: site
|
|
506
|
+
};
|
|
507
|
+
state.pendingAsync.add(pending);
|
|
508
|
+
return awaitable(start, () => {
|
|
509
|
+
state.pendingAsync.delete(pending);
|
|
510
|
+
});
|
|
511
|
+
};
|
|
512
|
+
return function poll(fn, options = {}) {
|
|
513
|
+
if (!engine.inTest()) throw new ExpectError("EXPECT_OUTSIDE_TEST", messages.outsideTest("poll"));
|
|
514
|
+
if (typeof fn !== "function") throw new ExpectError("EXPECT_INVALID_ARGUMENT", "expect.poll: the first argument must be a function");
|
|
515
|
+
const interval = options.interval ?? policy.poll.intervalMs;
|
|
516
|
+
const timeout = options.timeout ?? policy.poll.timeoutMs;
|
|
517
|
+
if (!isTime(interval) || !isTime(timeout)) throw new ExpectError("EXPECT_INVALID_ARGUMENT", "expect.poll: interval and timeout must be times in milliseconds");
|
|
518
|
+
const voice = (isNot) => new Proxy({}, { get(_target, key, receiver) {
|
|
519
|
+
if (typeof key !== "string") return void 0;
|
|
520
|
+
if (key === "not" && !isNot) return voice(true);
|
|
521
|
+
if (UNSUPPORTED.has(key)) throw new ExpectError("EXPECT_POLL_UNSUPPORTED", messages.pollUnsupported(key));
|
|
522
|
+
if (!engine.hasMatcher(key)) return Reflect.get(Object.prototype, key, receiver);
|
|
523
|
+
return chain(fn, interval, timeout, key, isNot);
|
|
524
|
+
} });
|
|
525
|
+
return voice(false);
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
// src/snapshot-matchers.ts
|
|
530
|
+
const INLINE_NOT_WRITTEN = "An inline snapshot would have to be written into the test file, and this project's dialect has no inline snapshot writer (T7.11). Run with --ci to treat a missing inline snapshot as a failure, or write the snapshot by hand.";
|
|
531
|
+
const INDENTATION_REGEX = /^([^\S\n]*)\S/m;
|
|
532
|
+
/**
|
|
533
|
+
* Takes off the indentation an inline snapshot was written with, when every line has it
|
|
534
|
+
* (index.ts L77-L110): the template literal in the source is indented to the call.
|
|
535
|
+
*/
|
|
536
|
+
function stripAddedIndentation(inlineSnapshot) {
|
|
537
|
+
const indentation = inlineSnapshot.match(INDENTATION_REGEX)?.[1];
|
|
538
|
+
if (!indentation) return inlineSnapshot;
|
|
539
|
+
const lines = inlineSnapshot.split("\n");
|
|
540
|
+
if (lines.length <= 2) return inlineSnapshot;
|
|
541
|
+
if (lines[0]?.trim() !== "" || lines.at(-1)?.trim() !== "") return inlineSnapshot;
|
|
542
|
+
for (let i = 1; i < lines.length - 1; i++) {
|
|
543
|
+
const line = lines[i] ?? "";
|
|
544
|
+
if (line !== "") {
|
|
545
|
+
if (line.indexOf(indentation) !== 0) return inlineSnapshot;
|
|
546
|
+
lines[i] = line.slice(indentation.length);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
lines[lines.length - 1] = "";
|
|
550
|
+
return lines.join("\n");
|
|
551
|
+
}
|
|
552
|
+
/** `jest-util`'s `isError`. */
|
|
553
|
+
function isError(value) {
|
|
554
|
+
switch (Object.prototype.toString.call(value)) {
|
|
555
|
+
case "[object Error]":
|
|
556
|
+
case "[object Exception]":
|
|
557
|
+
case "[object DOMException]": return true;
|
|
558
|
+
default: return value instanceof Error;
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
const isSnapshotState = (value) => typeof value === "object" && value !== null && typeof Reflect.get(value, "match") === "function" && typeof Reflect.get(value, "testName") === "function";
|
|
562
|
+
/**
|
|
563
|
+
* The file's snapshot state, from a matcher state's `snapshotState`, which may hold the dialect's
|
|
564
|
+
* view of it (`snapshot.contextView`); `undefined` when there is none.
|
|
565
|
+
*/
|
|
566
|
+
function findSnapshotState(value) {
|
|
567
|
+
const state = unwrapMatcherSnapshotState(value);
|
|
568
|
+
return isSnapshotState(state) ? state : void 0;
|
|
569
|
+
}
|
|
570
|
+
/** The file's snapshot state: Jest's "Snapshot state must be initialized". */
|
|
571
|
+
function stateOf(context, matcherName) {
|
|
572
|
+
const snapshotState = findSnapshotState(context.snapshotState);
|
|
573
|
+
if (snapshotState === void 0) throw new SnapshotError("SNAPSHOT_NOT_INITIALIZED", `expect(received).${matcherName}()\n\nSnapshot state must be initialized: the matcher ran outside a test file's run`);
|
|
574
|
+
return snapshotState;
|
|
575
|
+
}
|
|
576
|
+
function notAllowedWithNot(matcherName) {
|
|
577
|
+
return /* @__PURE__ */ new Error(`expect(received).not.${matcherName}()\n\nSnapshot matchers cannot be used with not`);
|
|
578
|
+
}
|
|
579
|
+
/** The test's title path for the snapshot's name. */
|
|
580
|
+
function titlePathOf(context) {
|
|
581
|
+
if (context.currentTestPath !== void 0) return context.currentTestPath;
|
|
582
|
+
return context.currentTestName === void 0 || context.currentTestName === "" ? [] : [context.currentTestName];
|
|
583
|
+
}
|
|
584
|
+
function infoOf(call, result, titlePath) {
|
|
585
|
+
const { state, context } = call;
|
|
586
|
+
return {
|
|
587
|
+
matcherName: call.matcherName,
|
|
588
|
+
isInline: call.isInline,
|
|
589
|
+
hint: call.hint ?? "",
|
|
590
|
+
currentTestName: state.testName(titlePath, void 0),
|
|
591
|
+
key: result.key,
|
|
592
|
+
count: result.count,
|
|
593
|
+
expand: state.expand || context.expand === true,
|
|
594
|
+
expected: result.expected,
|
|
595
|
+
actual: result.actual,
|
|
596
|
+
received: call.received,
|
|
597
|
+
...call.properties === void 0 ? {} : { properties: call.properties }
|
|
598
|
+
};
|
|
599
|
+
}
|
|
600
|
+
/** Jest's `_toMatchSnapshot` (index.ts L222-L367). */
|
|
601
|
+
function match(call) {
|
|
602
|
+
const { context, state, matcherName, isInline, hint, inlineSnapshot, properties } = call;
|
|
603
|
+
context.dontThrow();
|
|
604
|
+
let { received } = call;
|
|
605
|
+
if (context.isNot) throw notAllowedWithNot(matcherName);
|
|
606
|
+
const titlePath = titlePathOf(context);
|
|
607
|
+
const testName = state.testName(titlePath, hint);
|
|
608
|
+
const testId = context.currentTestId;
|
|
609
|
+
const testFailing = context.testFailing === true;
|
|
610
|
+
const base = {
|
|
611
|
+
name: matcherName,
|
|
612
|
+
...isInline ? {} : { snapshotPath: state.snapshotPath }
|
|
613
|
+
};
|
|
614
|
+
if (typeof properties === "object") {
|
|
615
|
+
if (typeof received !== "object" || received === null) throw new Error(`expect(received).${matcherName}(properties)\n\nreceived value must be an object when the matcher has properties\n\nReceived: ${String(received)}`);
|
|
616
|
+
const { iterableEquality, subsetEquality } = context.utils;
|
|
617
|
+
if (context.equals(received, properties, [...iterableEquality ? [iterableEquality] : [], ...subsetEquality ? [subsetEquality] : []])) received = deepMerge(received, properties);
|
|
618
|
+
else {
|
|
619
|
+
const key = state.fail(testName, testId);
|
|
620
|
+
const count = Number(/(\d+)$/.exec(key)?.[1] ?? 1);
|
|
621
|
+
const info = infoOf({
|
|
622
|
+
...call,
|
|
623
|
+
received
|
|
624
|
+
}, {
|
|
625
|
+
key,
|
|
626
|
+
count,
|
|
627
|
+
expected: void 0,
|
|
628
|
+
actual: ""
|
|
629
|
+
}, titlePath);
|
|
630
|
+
return {
|
|
631
|
+
...base,
|
|
632
|
+
pass: false,
|
|
633
|
+
message: () => state.messages.propertiesMismatch(info)
|
|
634
|
+
};
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
const result = state.match({
|
|
638
|
+
testName,
|
|
639
|
+
testId,
|
|
640
|
+
received,
|
|
641
|
+
inlineSnapshot,
|
|
642
|
+
isInline,
|
|
643
|
+
testFailing,
|
|
644
|
+
stack: call.stack
|
|
645
|
+
});
|
|
646
|
+
if (result.pass) return {
|
|
647
|
+
message: () => "",
|
|
648
|
+
pass: true,
|
|
649
|
+
name: matcherName
|
|
650
|
+
};
|
|
651
|
+
const info = infoOf({
|
|
652
|
+
...call,
|
|
653
|
+
received
|
|
654
|
+
}, result, titlePath);
|
|
655
|
+
if (result.inlineNotWritten) return {
|
|
656
|
+
...base,
|
|
657
|
+
pass: false,
|
|
658
|
+
message: () => `${matcherName}: ${INLINE_NOT_WRITTEN}`
|
|
659
|
+
};
|
|
660
|
+
return {
|
|
661
|
+
...base,
|
|
662
|
+
actual: result.actual,
|
|
663
|
+
expected: result.expected,
|
|
664
|
+
pass: false,
|
|
665
|
+
message: result.expected === void 0 ? () => state.messages.notWritten(info) : () => state.messages.mismatch(info)
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
function toMatchSnapshot(received, ...args) {
|
|
669
|
+
const matcherName = "toMatchSnapshot";
|
|
670
|
+
const state = stateOf(this, matcherName);
|
|
671
|
+
const [propertiesOrHint, hintArgument] = args;
|
|
672
|
+
let properties;
|
|
673
|
+
let hint;
|
|
674
|
+
if (args.length === 1 && typeof propertiesOrHint === "string") hint = propertiesOrHint;
|
|
675
|
+
else if (args.length >= 1) {
|
|
676
|
+
if (typeof propertiesOrHint !== "object" || propertiesOrHint === null) throw new Error(`expect(received).${matcherName}(properties${args.length === 2 ? ", hint" : ""})\n\nExpected properties must be an object\n\nExpected properties: ${String(propertiesOrHint)}${args.length === 2 && propertiesOrHint == null ? "\n\nTo provide a hint without properties: toMatchSnapshot('hint')" : ""}`);
|
|
677
|
+
properties = propertiesOrHint;
|
|
678
|
+
hint = typeof hintArgument === "string" ? hintArgument : void 0;
|
|
679
|
+
}
|
|
680
|
+
return match({
|
|
681
|
+
context: this,
|
|
682
|
+
state,
|
|
683
|
+
matcherName,
|
|
684
|
+
isInline: false,
|
|
685
|
+
hint,
|
|
686
|
+
inlineSnapshot: void 0,
|
|
687
|
+
properties,
|
|
688
|
+
received
|
|
689
|
+
});
|
|
690
|
+
}
|
|
691
|
+
function toMatchInlineSnapshot(received, ...args) {
|
|
692
|
+
const matcherName = "toMatchInlineSnapshot";
|
|
693
|
+
const state = stateOf(this, matcherName);
|
|
694
|
+
const [propertiesOrSnapshot, snapshotArgument] = args;
|
|
695
|
+
let properties;
|
|
696
|
+
let inlineSnapshot;
|
|
697
|
+
if (args.length === 1 && typeof propertiesOrSnapshot === "string") inlineSnapshot = propertiesOrSnapshot;
|
|
698
|
+
else if (args.length >= 1) {
|
|
699
|
+
if (typeof propertiesOrSnapshot !== "object" || propertiesOrSnapshot === null) throw new Error(`expect(received).${matcherName}(properties)\n\nExpected properties must be an object\n\nExpected properties: ${String(propertiesOrSnapshot)}`);
|
|
700
|
+
if (args.length === 2 && typeof snapshotArgument !== "string") throw new Error(`expect(received).${matcherName}(properties, snapshot)\n\nInline snapshot must be a string\n\nInline snapshot: ${String(snapshotArgument)}`);
|
|
701
|
+
properties = propertiesOrSnapshot;
|
|
702
|
+
inlineSnapshot = snapshotArgument;
|
|
703
|
+
}
|
|
704
|
+
return match({
|
|
705
|
+
context: this,
|
|
706
|
+
state,
|
|
707
|
+
matcherName,
|
|
708
|
+
isInline: true,
|
|
709
|
+
hint: void 0,
|
|
710
|
+
inlineSnapshot: typeof inlineSnapshot === "string" ? stripAddedIndentation(inlineSnapshot) : void 0,
|
|
711
|
+
properties,
|
|
712
|
+
received,
|
|
713
|
+
stack: matcherCallStack(this.error)
|
|
714
|
+
});
|
|
715
|
+
}
|
|
716
|
+
/**
|
|
717
|
+
* The text of an error as `toThrowErrorMatchingSnapshot` stores it in Jest: the message, then
|
|
718
|
+
* `\nCause: ` and the message of each cause down the chain (index.ts L552-L564). As in Jest, the
|
|
719
|
+
* message is kept as it is (a thrown object without one stores `undefined`) and a thrown primitive
|
|
720
|
+
* fails the test with the `in` operator's own TypeError.
|
|
721
|
+
*/
|
|
722
|
+
function messageWithCauses(thrown) {
|
|
723
|
+
let error = thrown;
|
|
724
|
+
let message = error.message;
|
|
725
|
+
while ("cause" in error) {
|
|
726
|
+
const cause = error.cause;
|
|
727
|
+
if (isError(cause)) {
|
|
728
|
+
error = cause;
|
|
729
|
+
message = `${String(message)}\nCause: ${cause.message}`;
|
|
730
|
+
} else {
|
|
731
|
+
if (typeof cause === "string") message = `${String(message)}\nCause: ${cause}`;
|
|
732
|
+
break;
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
return message;
|
|
736
|
+
}
|
|
737
|
+
/** Jest's `_toThrowErrorMatchingSnapshot` (index.ts L494-L567). */
|
|
738
|
+
function matchThrown(context, received, options) {
|
|
739
|
+
const { matcherName, isInline, hint, inlineSnapshot, fromPromise } = options;
|
|
740
|
+
context.dontThrow();
|
|
741
|
+
const state = stateOf(context, matcherName);
|
|
742
|
+
if (!fromPromise && typeof received !== "function") throw new Error(`expect(received).${matcherName}()\n\nreceived value must be a function\n\nReceived: ${String(received)}`);
|
|
743
|
+
if (context.isNot) throw notAllowedWithNot(matcherName);
|
|
744
|
+
let error;
|
|
745
|
+
if (fromPromise) error = received;
|
|
746
|
+
else try {
|
|
747
|
+
received();
|
|
748
|
+
} catch (receivedError) {
|
|
749
|
+
error = receivedError;
|
|
750
|
+
}
|
|
751
|
+
if (error === void 0) throw new Error(`expect(received).${matcherName}()\n\nReceived function did not throw`);
|
|
752
|
+
return match({
|
|
753
|
+
context,
|
|
754
|
+
state,
|
|
755
|
+
matcherName,
|
|
756
|
+
isInline,
|
|
757
|
+
hint,
|
|
758
|
+
inlineSnapshot,
|
|
759
|
+
properties: void 0,
|
|
760
|
+
received: state.throwErrorBody === "message" ? messageWithCauses(error) : error,
|
|
761
|
+
stack: options.stack
|
|
762
|
+
});
|
|
763
|
+
}
|
|
764
|
+
function toThrowErrorMatchingSnapshot(received, hint, fromPromise) {
|
|
765
|
+
return matchThrown(this, received, {
|
|
766
|
+
matcherName: "toThrowErrorMatchingSnapshot",
|
|
767
|
+
isInline: false,
|
|
768
|
+
hint: typeof hint === "string" ? hint : void 0,
|
|
769
|
+
inlineSnapshot: void 0,
|
|
770
|
+
fromPromise: fromPromise === true
|
|
771
|
+
});
|
|
772
|
+
}
|
|
773
|
+
function toThrowErrorMatchingInlineSnapshot(received, inlineSnapshot, fromPromise) {
|
|
774
|
+
const matcherName = "toThrowErrorMatchingInlineSnapshot";
|
|
775
|
+
if (inlineSnapshot !== void 0 && typeof inlineSnapshot !== "string") throw new Error(`expect(received).${matcherName}(snapshot)\n\nInline snapshot must be a string\n\nInline snapshot: ${String(inlineSnapshot)}`);
|
|
776
|
+
return matchThrown(this, received, {
|
|
777
|
+
matcherName,
|
|
778
|
+
isInline: true,
|
|
779
|
+
hint: void 0,
|
|
780
|
+
inlineSnapshot: inlineSnapshot === void 0 ? void 0 : stripAddedIndentation(inlineSnapshot),
|
|
781
|
+
fromPromise: fromPromise === true,
|
|
782
|
+
stack: matcherCallStack(this.error)
|
|
783
|
+
});
|
|
784
|
+
}
|
|
785
|
+
/** Vitest's `toMatchFileSnapshot(file, hint?)`: the value is compared with a file's contents. */
|
|
786
|
+
async function toMatchFileSnapshot(received, file, hint) {
|
|
787
|
+
const matcherName = "toMatchFileSnapshot";
|
|
788
|
+
const state = stateOf(this, matcherName);
|
|
789
|
+
if (this.isNot) throw notAllowedWithNot(matcherName);
|
|
790
|
+
if (typeof file !== "string" || file === "") throw new Error(`expect(received).${matcherName}(file)\n\nThe file must be a path, relative to the test file or absolute`);
|
|
791
|
+
const path = resolve(dirname(state.testPath), file);
|
|
792
|
+
if (path === state.snapshotPath) throw new Error(`File snapshot cannot use the same path as the test snapshot file: ${path}`);
|
|
793
|
+
const titlePath = titlePathOf(this);
|
|
794
|
+
const result = state.matchRaw({
|
|
795
|
+
testName: state.testName(titlePath, typeof hint === "string" ? hint : void 0),
|
|
796
|
+
...this.currentTestId === void 0 ? {} : { testId: this.currentTestId },
|
|
797
|
+
received,
|
|
798
|
+
file: path,
|
|
799
|
+
existing: SnapshotState.readRaw(path)
|
|
800
|
+
});
|
|
801
|
+
if (result.pass) return {
|
|
802
|
+
message: () => "",
|
|
803
|
+
pass: true,
|
|
804
|
+
name: matcherName
|
|
805
|
+
};
|
|
806
|
+
const info = infoOf({
|
|
807
|
+
context: this,
|
|
808
|
+
state,
|
|
809
|
+
matcherName,
|
|
810
|
+
isInline: false,
|
|
811
|
+
hint: typeof hint === "string" ? hint : void 0,
|
|
812
|
+
inlineSnapshot: void 0,
|
|
813
|
+
properties: void 0,
|
|
814
|
+
received
|
|
815
|
+
}, result, titlePath);
|
|
816
|
+
return {
|
|
817
|
+
name: matcherName,
|
|
818
|
+
pass: false,
|
|
819
|
+
actual: result.actual,
|
|
820
|
+
expected: result.expected,
|
|
821
|
+
message: result.expected === void 0 ? () => state.messages.notWritten(info) : () => state.messages.mismatch(info)
|
|
822
|
+
};
|
|
823
|
+
}
|
|
824
|
+
/**
|
|
825
|
+
* The snapshot matchers a dialect's table includes, and the `.resolves`/`.rejects` form of the
|
|
826
|
+
* two that read a thrown error (Jest's `getPromiseMatcher`: the settled value is the error, so the
|
|
827
|
+
* matcher is told not to call it).
|
|
828
|
+
* @public
|
|
829
|
+
*/
|
|
830
|
+
function snapshotMatchers(options) {
|
|
831
|
+
const matchers = {
|
|
832
|
+
toMatchSnapshot,
|
|
833
|
+
toMatchInlineSnapshot,
|
|
834
|
+
toThrowErrorMatchingSnapshot,
|
|
835
|
+
toThrowErrorMatchingInlineSnapshot,
|
|
836
|
+
...options.fileSnapshot ? { toMatchFileSnapshot } : {}
|
|
837
|
+
};
|
|
838
|
+
const fromPromise = (matcher) => function(received, argument) {
|
|
839
|
+
return matcher.call(this, received, argument, true);
|
|
840
|
+
};
|
|
841
|
+
return {
|
|
842
|
+
matchers,
|
|
843
|
+
promiseMatchers: {
|
|
844
|
+
toThrowErrorMatchingSnapshot: fromPromise(matchers.toThrowErrorMatchingSnapshot),
|
|
845
|
+
toThrowErrorMatchingInlineSnapshot: fromPromise(matchers.toThrowErrorMatchingInlineSnapshot)
|
|
846
|
+
}
|
|
847
|
+
};
|
|
848
|
+
}
|
|
849
|
+
/**
|
|
850
|
+
* Adds a snapshot serializer to the running file's state (`expect.addSnapshotSerializer`). Jest's
|
|
851
|
+
* list is the module's, which is one per test file; here it is the file's snapshot state's.
|
|
852
|
+
* @internal
|
|
853
|
+
*/
|
|
854
|
+
function addSnapshotSerializer(context, plugin) {
|
|
855
|
+
const snapshotState = findSnapshotState(context.snapshotState);
|
|
856
|
+
if (snapshotState === void 0) throw new SnapshotError("SNAPSHOT_NOT_INITIALIZED", "expect.addSnapshotSerializer() ran outside a test file's run: there is no snapshot state to add the serializer to");
|
|
857
|
+
snapshotState.addSerializer(plugin);
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
// src/expect.ts
|
|
861
|
+
/**
|
|
862
|
+
* The error a failed assertion throws under `errorShape: 'matcher-result'`: an `Error` whose text
|
|
863
|
+
* is in `message`, with the matcher's result attached (Jest's `JestAssertionError`). Its `name`
|
|
864
|
+
* is `Error`, so reports print `Error: …` as Jest's do.
|
|
865
|
+
* @public
|
|
866
|
+
*/
|
|
867
|
+
var MatcherResultError = class extends Error {
|
|
868
|
+
matcherResult;
|
|
869
|
+
};
|
|
870
|
+
/**
|
|
871
|
+
* Jest's flag for built-in matchers (`$$jest-internal-matcher`), set on the matcher function itself.
|
|
872
|
+
* Their failures are re-anchored at the caller, and they're called without the external trap.
|
|
873
|
+
*/
|
|
874
|
+
const INTERNAL_MATCHER_FLAG = Symbol.for("$$jest-internal-matcher");
|
|
875
|
+
const isInternal = (matcher) => Reflect.get(matcher, INTERNAL_MATCHER_FLAG) === true;
|
|
876
|
+
/**
|
|
877
|
+
* Builds a dialect's `expect`. Throws `EXPECT_NOT_IMPLEMENTED` for policy values a later task
|
|
878
|
+
* builds, rather than running them half-way.
|
|
879
|
+
* @public
|
|
880
|
+
*/
|
|
881
|
+
function createExpect(options) {
|
|
882
|
+
const { policy, table, source } = options;
|
|
883
|
+
checkPolicy(policy);
|
|
884
|
+
const track = options.unawaited === "fail";
|
|
885
|
+
const registry = options.registry ?? createMatcherRegistry();
|
|
886
|
+
registry.utils = table.utils;
|
|
887
|
+
const policyTesters = equalityTesters(policy.equality);
|
|
888
|
+
registry.customEqualityTesters.push(...policyTesters);
|
|
889
|
+
const { messages } = table;
|
|
890
|
+
/** The table's promise forms: dialect code, so their errors are re-anchored like built-ins'. */
|
|
891
|
+
const promiseForms = new WeakSet(Object.values(table.promiseMatchers));
|
|
892
|
+
const getState = () => source.current();
|
|
893
|
+
/**
|
|
894
|
+
* One call of a matcher. `settled` is set under `.resolves`/`.rejects`; a direct call reads the
|
|
895
|
+
* state now and anchors above `throwingMatcher`, as Jest does.
|
|
896
|
+
*/
|
|
897
|
+
const makeThrowingMatcher = (matcher, isNot, promise, actual, settled, soft = false) => function throwingMatcher(...args) {
|
|
898
|
+
let throws = !soft;
|
|
899
|
+
const internal = isInternal(matcher);
|
|
900
|
+
const state = settled?.state ?? getState();
|
|
901
|
+
const above = settled?.above ?? throwingMatcher;
|
|
902
|
+
const matcherContext = {
|
|
903
|
+
...state,
|
|
904
|
+
customTesters: registry.customEqualityTesters,
|
|
905
|
+
dontThrow: () => {
|
|
906
|
+
throws = false;
|
|
907
|
+
return false;
|
|
908
|
+
},
|
|
909
|
+
equals,
|
|
910
|
+
utils: registry.utils,
|
|
911
|
+
error: settled?.error,
|
|
912
|
+
isNot,
|
|
913
|
+
promise
|
|
914
|
+
};
|
|
915
|
+
const processResult = (result, at, asyncError) => {
|
|
916
|
+
let valid;
|
|
917
|
+
try {
|
|
918
|
+
valid = validateResult(result, messages.invalidResult);
|
|
919
|
+
} catch (error) {
|
|
920
|
+
throw anchor(error, at);
|
|
921
|
+
}
|
|
922
|
+
state.assertionCalls++;
|
|
923
|
+
if (valid.pass && isNot || !valid.pass && !isNot) {
|
|
924
|
+
const message = getMessage(valid, messages.noMessage, at);
|
|
925
|
+
let error = settled?.error ?? asyncError;
|
|
926
|
+
if (error) error.message = message;
|
|
927
|
+
else error = anchor(new MatcherResultError(message), at);
|
|
928
|
+
error.matcherResult = {
|
|
929
|
+
...valid,
|
|
930
|
+
message
|
|
931
|
+
};
|
|
932
|
+
if (throws) throw error;
|
|
933
|
+
state.suppressedErrors.push(error);
|
|
934
|
+
} else state.numPassingAsserts++;
|
|
935
|
+
};
|
|
936
|
+
const handleError = (error) => {
|
|
937
|
+
if ((internal || promiseForms.has(matcher)) && typeof error === "object" && error !== null && !(error instanceof MatcherResultError) && Reflect.get(error, "name") !== "PrettyFormatPluginError") Error.captureStackTrace(error, above);
|
|
938
|
+
throw error;
|
|
939
|
+
};
|
|
940
|
+
const callable = matcher;
|
|
941
|
+
let potentialResult;
|
|
942
|
+
try {
|
|
943
|
+
potentialResult = internal ? callable.call(matcherContext, actual, ...args) : (function __EXTERNAL_MATCHER_TRAP__() {
|
|
944
|
+
return callable.call(matcherContext, actual, ...args);
|
|
945
|
+
})();
|
|
946
|
+
if (isPromise(potentialResult)) {
|
|
947
|
+
const asyncError = capturedError(above);
|
|
948
|
+
const chained = potentialResult.then(function onMatcherResult(result) {
|
|
949
|
+
processResult(result, onMatcherResult, asyncError);
|
|
950
|
+
});
|
|
951
|
+
return anchored(() => chained.catch(handleError), above);
|
|
952
|
+
}
|
|
953
|
+
return processResult(potentialResult, above);
|
|
954
|
+
} catch (error) {
|
|
955
|
+
return handleError(error);
|
|
956
|
+
}
|
|
957
|
+
};
|
|
958
|
+
const makeSettledMatcher = (matcherName, matcher, { actual, isNot, promise, outer, soft }) => function settledMatcher(...args) {
|
|
959
|
+
const call = {
|
|
960
|
+
matcherName,
|
|
961
|
+
isNot,
|
|
962
|
+
promise
|
|
963
|
+
};
|
|
964
|
+
const state = getState();
|
|
965
|
+
const actualWrapper = typeof actual === "function" ? actual() : actual;
|
|
966
|
+
if (!isPromise(actualWrapper)) throw anchor(new MatcherResultError(messages.notAPromise(call, actual)), settledMatcher);
|
|
967
|
+
const error = capturedError(settledMatcher);
|
|
968
|
+
const outerErr = outer ?? new MatcherResultError();
|
|
969
|
+
const wrong = (message) => {
|
|
970
|
+
outerErr.message = message;
|
|
971
|
+
throw outerErr;
|
|
972
|
+
};
|
|
973
|
+
const settle = (value, above) => makeThrowingMatcher(matcher, isNot, promise, value, {
|
|
974
|
+
state,
|
|
975
|
+
above,
|
|
976
|
+
error
|
|
977
|
+
}, soft)(...args);
|
|
978
|
+
const chained = actualWrapper.then(function onResolved(result) {
|
|
979
|
+
if (promise === "rejects") wrong(messages.resolvedInsteadOfRejected(call, result));
|
|
980
|
+
return settle(result, onResolved);
|
|
981
|
+
}, function onRejected(reason) {
|
|
982
|
+
if (promise === "resolves") wrong(messages.rejectedInsteadOfResolved(call, reason));
|
|
983
|
+
return settle(reason, onRejected);
|
|
984
|
+
});
|
|
985
|
+
const outcome = soft ? Promise.resolve(chained).then(void 0, (failure) => {
|
|
986
|
+
state.suppressedErrors.push(failure instanceof Error ? failure : new Error(String(failure)));
|
|
987
|
+
}) : chained;
|
|
988
|
+
if (!track) return outcome;
|
|
989
|
+
const pending = {
|
|
990
|
+
kind: "settled",
|
|
991
|
+
call,
|
|
992
|
+
error: capturedError(settledMatcher)
|
|
993
|
+
};
|
|
994
|
+
state.pendingAsync.add(pending);
|
|
995
|
+
Promise.resolve(outcome).catch(() => void 0);
|
|
996
|
+
return awaitable(() => Promise.resolve(outcome), () => {
|
|
997
|
+
state.pendingAsync.delete(pending);
|
|
998
|
+
});
|
|
999
|
+
};
|
|
1000
|
+
/** What Jest's plain expectation object has as own keys, for this voice. */
|
|
1001
|
+
const keysOf = ({ isNot, promise }) => {
|
|
1002
|
+
const names = Object.keys(registry.matchers);
|
|
1003
|
+
if (isNot) return names;
|
|
1004
|
+
return promise === "" ? [
|
|
1005
|
+
"not",
|
|
1006
|
+
"rejects",
|
|
1007
|
+
"resolves",
|
|
1008
|
+
...names
|
|
1009
|
+
] : ["not", ...names];
|
|
1010
|
+
};
|
|
1011
|
+
/** `keysOf(target).includes(key)`, without building the list (`in` and descriptors per key). */
|
|
1012
|
+
const hasKey = ({ isNot, promise }, key) => key === "not" && !isNot || (key === "resolves" || key === "rejects") && !isNot && promise === "" || Object.prototype.propertyIsEnumerable.call(registry.matchers, key);
|
|
1013
|
+
function get(target, key, receiver) {
|
|
1014
|
+
if (typeof key !== "string") return void 0;
|
|
1015
|
+
if (key === "not") {
|
|
1016
|
+
if (target.isNot) return void 0;
|
|
1017
|
+
const { actual, promise, outer, soft } = target;
|
|
1018
|
+
return assertion({
|
|
1019
|
+
actual,
|
|
1020
|
+
isNot: true,
|
|
1021
|
+
promise,
|
|
1022
|
+
outer,
|
|
1023
|
+
soft
|
|
1024
|
+
});
|
|
1025
|
+
}
|
|
1026
|
+
if (key === "resolves" || key === "rejects") {
|
|
1027
|
+
if (target.isNot || target.promise !== "") return void 0;
|
|
1028
|
+
const outer = target.outer ?? capturedError(get);
|
|
1029
|
+
return assertion({
|
|
1030
|
+
actual: target.actual,
|
|
1031
|
+
isNot: false,
|
|
1032
|
+
promise: key,
|
|
1033
|
+
outer,
|
|
1034
|
+
soft: target.soft
|
|
1035
|
+
});
|
|
1036
|
+
}
|
|
1037
|
+
const matcher = registry.matchers[key];
|
|
1038
|
+
if (matcher === void 0) return Reflect.get(Object.prototype, key, receiver);
|
|
1039
|
+
if (target.promise === "") return makeThrowingMatcher(matcher, target.isNot, "", target.actual, void 0, target.soft);
|
|
1040
|
+
const promiseForm = Object.hasOwn(table.promiseMatchers, key) ? table.promiseMatchers[key] : void 0;
|
|
1041
|
+
return makeSettledMatcher(key, promiseForm ?? matcher, target);
|
|
1042
|
+
}
|
|
1043
|
+
const handler = {
|
|
1044
|
+
get,
|
|
1045
|
+
ownKeys: (target) => keysOf(target),
|
|
1046
|
+
has: (target, key) => typeof key === "string" && hasKey(target, key) || key in Object.prototype,
|
|
1047
|
+
getOwnPropertyDescriptor(target, key) {
|
|
1048
|
+
if (typeof key !== "string" || !hasKey(target, key)) return void 0;
|
|
1049
|
+
return {
|
|
1050
|
+
configurable: true,
|
|
1051
|
+
enumerable: true,
|
|
1052
|
+
writable: true,
|
|
1053
|
+
value: get(target, key, target)
|
|
1054
|
+
};
|
|
1055
|
+
}
|
|
1056
|
+
};
|
|
1057
|
+
const assertion = (target) => new Proxy(target, handler);
|
|
1058
|
+
function expect(actual, ...rest) {
|
|
1059
|
+
if (rest.length > 0) throw anchor(new Error(messages.tooManyArguments()), expect);
|
|
1060
|
+
const outer = typeof actual === "function" || types.isPromise(actual) ? capturedError(expect) : void 0;
|
|
1061
|
+
return assertion({
|
|
1062
|
+
actual,
|
|
1063
|
+
isNot: false,
|
|
1064
|
+
promise: "",
|
|
1065
|
+
outer,
|
|
1066
|
+
soft: false
|
|
1067
|
+
});
|
|
1068
|
+
}
|
|
1069
|
+
/** `expect`, but a failed assertion is recorded and the test goes on. */
|
|
1070
|
+
function soft(actual, ...rest) {
|
|
1071
|
+
if (rest.length > 0) throw anchor(new Error(messages.tooManyArguments()), soft);
|
|
1072
|
+
if (source.current() === source.file()) throw anchor(new ExpectError("EXPECT_OUTSIDE_TEST", messages.outsideTest("soft")), soft);
|
|
1073
|
+
const outer = typeof actual === "function" || types.isPromise(actual) ? capturedError(soft) : void 0;
|
|
1074
|
+
return assertion({
|
|
1075
|
+
actual,
|
|
1076
|
+
isNot: false,
|
|
1077
|
+
promise: "",
|
|
1078
|
+
outer,
|
|
1079
|
+
soft: true
|
|
1080
|
+
});
|
|
1081
|
+
}
|
|
1082
|
+
const not = { ...table.asymmetricNot };
|
|
1083
|
+
const defineAsymmetric = (owner, name, value) => {
|
|
1084
|
+
Object.defineProperty(owner, name, {
|
|
1085
|
+
configurable: true,
|
|
1086
|
+
enumerable: true,
|
|
1087
|
+
value,
|
|
1088
|
+
writable: true
|
|
1089
|
+
});
|
|
1090
|
+
};
|
|
1091
|
+
/** Jest's `setMatchers` (jestMatchersObject.ts L56–L117), key by key. */
|
|
1092
|
+
const register = (matchers, internal, caller) => {
|
|
1093
|
+
for (const name of anchored(() => Object.keys(matchers), caller)) {
|
|
1094
|
+
const matcher = matchers[name];
|
|
1095
|
+
if (typeof matcher !== "function") throw anchor(new TypeError(messages.invalidMatcher(name, matcher)), caller);
|
|
1096
|
+
anchored(() => Object.defineProperty(matcher, INTERNAL_MATCHER_FLAG, { value: internal }), caller);
|
|
1097
|
+
if (!internal) {
|
|
1098
|
+
const build = table.customAsymmetric(name, matcher);
|
|
1099
|
+
defineAsymmetric(expect, name, (...sample) => build(false, sample));
|
|
1100
|
+
defineAsymmetric(not, name, (...sample) => build(true, sample));
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
Object.assign(registry.matchers, matchers);
|
|
1104
|
+
};
|
|
1105
|
+
function extend(matchers) {
|
|
1106
|
+
register(matchers, false, extend);
|
|
1107
|
+
}
|
|
1108
|
+
function addEqualityTesters(testers) {
|
|
1109
|
+
if (!Array.isArray(testers)) throw anchor(new TypeError(messages.invalidTesters(testers)), addEqualityTesters);
|
|
1110
|
+
const { customEqualityTesters } = registry;
|
|
1111
|
+
customEqualityTesters.splice(customEqualityTesters.length - policyTesters.length, 0, ...testers);
|
|
1112
|
+
}
|
|
1113
|
+
function assertions(expected) {
|
|
1114
|
+
const error = anchor(/* @__PURE__ */ new Error(), assertions);
|
|
1115
|
+
Object.assign(getState(), {
|
|
1116
|
+
expectedAssertionsNumber: expected,
|
|
1117
|
+
expectedAssertionsNumberError: error
|
|
1118
|
+
});
|
|
1119
|
+
}
|
|
1120
|
+
function hasAssertions(...args) {
|
|
1121
|
+
const error = anchor(/* @__PURE__ */ new Error(), hasAssertions);
|
|
1122
|
+
anchored(() => messages.ensureNoExpected(args[0], ".hasAssertions"), hasAssertions);
|
|
1123
|
+
Object.assign(getState(), {
|
|
1124
|
+
isExpectingAssertions: true,
|
|
1125
|
+
isExpectingAssertionsError: error
|
|
1126
|
+
});
|
|
1127
|
+
}
|
|
1128
|
+
/** `expect.unreachable(message)`: only on a dialect whose table words it. */
|
|
1129
|
+
const unreachableText = messages.unreachable?.bind(messages);
|
|
1130
|
+
function unreachable(message) {
|
|
1131
|
+
throw anchor(new MatcherResultError(unreachableText?.(message)), unreachable);
|
|
1132
|
+
}
|
|
1133
|
+
const poll = policy.poll.enabled ? createPoll({
|
|
1134
|
+
policy,
|
|
1135
|
+
messages,
|
|
1136
|
+
timers: options.pollTimers,
|
|
1137
|
+
track,
|
|
1138
|
+
state: getState,
|
|
1139
|
+
inTest: () => source.current() !== source.file(),
|
|
1140
|
+
hasMatcher: (name) => registry.matchers[name] !== void 0,
|
|
1141
|
+
capture: capturedError,
|
|
1142
|
+
run: function pollTry(name, isNot, value, args, state) {
|
|
1143
|
+
const matcher = registry.matchers[name];
|
|
1144
|
+
if (matcher === void 0) throw new TypeError(`${name} is not a matcher`);
|
|
1145
|
+
const error = capturedError(pollTry);
|
|
1146
|
+
return makeThrowingMatcher(matcher, isNot, "", value, {
|
|
1147
|
+
state,
|
|
1148
|
+
above: pollTry,
|
|
1149
|
+
error
|
|
1150
|
+
})(...args);
|
|
1151
|
+
}
|
|
1152
|
+
}) : void 0;
|
|
1153
|
+
const statics = {
|
|
1154
|
+
...table.asymmetric,
|
|
1155
|
+
...policy.soft ? { soft } : {},
|
|
1156
|
+
...poll === void 0 ? {} : { poll },
|
|
1157
|
+
...unreachableText === void 0 ? {} : { unreachable },
|
|
1158
|
+
not,
|
|
1159
|
+
extend,
|
|
1160
|
+
addEqualityTesters,
|
|
1161
|
+
assertions,
|
|
1162
|
+
hasAssertions,
|
|
1163
|
+
getState,
|
|
1164
|
+
setState(state) {
|
|
1165
|
+
Object.assign(getState(), state);
|
|
1166
|
+
},
|
|
1167
|
+
addSnapshotSerializer(plugin) {
|
|
1168
|
+
addSnapshotSerializer(getState(), plugin);
|
|
1169
|
+
}
|
|
1170
|
+
};
|
|
1171
|
+
register(table.matchers, true, createExpect);
|
|
1172
|
+
return Object.assign(expect, statics);
|
|
1173
|
+
}
|
|
1174
|
+
/** The policy values the engine builds; the rest throw rather than run half-way. */
|
|
1175
|
+
function checkPolicy(policy) {
|
|
1176
|
+
const missing = [];
|
|
1177
|
+
if (policy.matcherTable === null) throw new ExpectError("EXPECT_NO_MATCHER_TABLE", "ExpectPolicy.matcherTable is null: the neutral matcher table is not built yet");
|
|
1178
|
+
if (policy.errorShape !== "matcher-result") missing.push(`errorShape: '${policy.errorShape}' (T7.6)`);
|
|
1179
|
+
if (missing.length > 0) throw new ExpectError("EXPECT_NOT_IMPLEMENTED", `not built yet: ${missing.join(", ")}`);
|
|
1180
|
+
}
|
|
1181
|
+
/** Jest's `jest-util` `isPromise`: any thenable. */
|
|
1182
|
+
function isPromise(candidate) {
|
|
1183
|
+
return candidate != null && (typeof candidate === "object" || typeof candidate === "function") && typeof Reflect.get(candidate, "then") === "function";
|
|
1184
|
+
}
|
|
1185
|
+
/**
|
|
1186
|
+
* Jest's `_validateResult` (index.ts L422–L438): `{ pass: boolean, message?: string | function }`.
|
|
1187
|
+
* Its expression is kept as written, so a `null` result reads `.pass` and throws V8's
|
|
1188
|
+
* `Cannot read properties of null (reading 'pass')`, as in Jest.
|
|
1189
|
+
*/
|
|
1190
|
+
function validateResult(result, invalid) {
|
|
1191
|
+
const shaped = result;
|
|
1192
|
+
if (typeof result !== "object" || typeof shaped.pass !== "boolean" || shaped.message && typeof shaped.message !== "string" && typeof shaped.message !== "function") throw new Error(invalid(result));
|
|
1193
|
+
return result;
|
|
1194
|
+
}
|
|
1195
|
+
/**
|
|
1196
|
+
* Jest's `getMessage`: `(message && message()) || noMessage`. A string `message` passes
|
|
1197
|
+
* validation and then throws `message is not a function` here, as in Jest; the name `message` is
|
|
1198
|
+
* kept for that text, and only that error, thrown from this frame, is anchored above `above`. An
|
|
1199
|
+
* error a custom matcher's own `message` throws keeps its frames, as in Jest.
|
|
1200
|
+
*/
|
|
1201
|
+
function getMessage(result, noMessage, above) {
|
|
1202
|
+
const raw = result.message;
|
|
1203
|
+
if (raw && typeof raw !== "function") {
|
|
1204
|
+
const message = raw;
|
|
1205
|
+
return anchored(() => message(), above);
|
|
1206
|
+
}
|
|
1207
|
+
const message = raw;
|
|
1208
|
+
return message && message() || noMessage();
|
|
1209
|
+
}
|
|
1210
|
+
/** Re-anchors an error the engine throws so its top frame is the user's call. */
|
|
1211
|
+
function anchor(error, above) {
|
|
1212
|
+
if (typeof error === "object" && error !== null) Error.captureStackTrace(error, above);
|
|
1213
|
+
return error;
|
|
1214
|
+
}
|
|
1215
|
+
/**
|
|
1216
|
+
* An empty `MatcherResultError` whose stack starts above `above`. The constructor's own stack is
|
|
1217
|
+
* switched off, since `captureStackTrace` replaces it anyway: on `expect(fn)`, `expect(promise)` and
|
|
1218
|
+
* every `.resolves`/`.rejects` call that halves the cost. The header is still taken lazily, so a
|
|
1219
|
+
* message set later shows in it.
|
|
1220
|
+
*/
|
|
1221
|
+
function capturedError(above) {
|
|
1222
|
+
if (!Object.hasOwn(Error, "stackTraceLimit")) return anchor(new MatcherResultError(), above);
|
|
1223
|
+
const limit = Error.stackTraceLimit;
|
|
1224
|
+
Error.stackTraceLimit = 0;
|
|
1225
|
+
let error;
|
|
1226
|
+
try {
|
|
1227
|
+
error = new MatcherResultError();
|
|
1228
|
+
} finally {
|
|
1229
|
+
Error.stackTraceLimit = limit;
|
|
1230
|
+
}
|
|
1231
|
+
Error.captureStackTrace(error, above);
|
|
1232
|
+
return error;
|
|
1233
|
+
}
|
|
1234
|
+
/** Runs `fn`, re-anchoring what it throws above `above`. */
|
|
1235
|
+
function anchored(fn, above) {
|
|
1236
|
+
try {
|
|
1237
|
+
return fn();
|
|
1238
|
+
} catch (error) {
|
|
1239
|
+
throw anchor(error, above);
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
// src/state.ts
|
|
1244
|
+
/** A run's key among a test's runs: a number, so the per-assertion lookup builds no string. */
|
|
1245
|
+
const runKey = ({ attempt, repeat }) => repeat * 1048576 + attempt;
|
|
1246
|
+
/**
|
|
1247
|
+
* Builds the state source from the worker's current-test lookup (core's `currentTest`). Typed by
|
|
1248
|
+
* `@provino/types`' `CurrentTest`, so the engine never imports core (Track 7 §Per-test state).
|
|
1249
|
+
* @public
|
|
1250
|
+
*/
|
|
1251
|
+
function createStateSource(currentTest, options) {
|
|
1252
|
+
const { nameSeparator, expand, outsideTestCounts = "drop" } = options;
|
|
1253
|
+
const carry = outsideTestCounts === "next-test";
|
|
1254
|
+
let fileState = newFileState(expand, void 0);
|
|
1255
|
+
/** Each test's runs, by `runKey`. */
|
|
1256
|
+
let tests = /* @__PURE__ */ new Map();
|
|
1257
|
+
let lastFrame;
|
|
1258
|
+
let lastState = fileState;
|
|
1259
|
+
return {
|
|
1260
|
+
current() {
|
|
1261
|
+
const frame = currentTest.get();
|
|
1262
|
+
if (frame?.test == null) return fileState;
|
|
1263
|
+
if (frame === lastFrame) return lastState;
|
|
1264
|
+
const { test } = frame;
|
|
1265
|
+
let runs = tests.get(test.id);
|
|
1266
|
+
if (runs === void 0) {
|
|
1267
|
+
runs = /* @__PURE__ */ new Map();
|
|
1268
|
+
tests.set(test.id, runs);
|
|
1269
|
+
}
|
|
1270
|
+
const key = runKey(frame);
|
|
1271
|
+
let state = runs.get(key);
|
|
1272
|
+
if (state === void 0) {
|
|
1273
|
+
state = newAttemptState(fileState, test.id, test, nameSeparator);
|
|
1274
|
+
if (carry) moveCounters(fileState, state);
|
|
1275
|
+
runs.set(key, state);
|
|
1276
|
+
}
|
|
1277
|
+
lastFrame = frame;
|
|
1278
|
+
lastState = state;
|
|
1279
|
+
return state;
|
|
1280
|
+
},
|
|
1281
|
+
file() {
|
|
1282
|
+
return fileState;
|
|
1283
|
+
},
|
|
1284
|
+
startFile(testPath) {
|
|
1285
|
+
fileState = newFileState(expand, testPath);
|
|
1286
|
+
tests = /* @__PURE__ */ new Map();
|
|
1287
|
+
lastFrame = void 0;
|
|
1288
|
+
},
|
|
1289
|
+
stateOf(testId, run) {
|
|
1290
|
+
return tests.get(testId)?.get(runKey(run));
|
|
1291
|
+
},
|
|
1292
|
+
settle(testId, run) {
|
|
1293
|
+
const found = tests.get(testId)?.get(runKey(run));
|
|
1294
|
+
if (found !== void 0 || !carry || !hasCounts(fileState)) return found;
|
|
1295
|
+
const state = newAttemptState(fileState, testId, void 0, nameSeparator);
|
|
1296
|
+
moveCounters(fileState, state);
|
|
1297
|
+
let runs = tests.get(testId);
|
|
1298
|
+
if (runs === void 0) {
|
|
1299
|
+
runs = /* @__PURE__ */ new Map();
|
|
1300
|
+
tests.set(testId, runs);
|
|
1301
|
+
}
|
|
1302
|
+
runs.set(runKey(run), state);
|
|
1303
|
+
return state;
|
|
1304
|
+
}
|
|
1305
|
+
};
|
|
1306
|
+
}
|
|
1307
|
+
function newFileState(expand, testPath) {
|
|
1308
|
+
return {
|
|
1309
|
+
...freshCounters(),
|
|
1310
|
+
expand,
|
|
1311
|
+
...testPath === void 0 ? {} : { testPath }
|
|
1312
|
+
};
|
|
1313
|
+
}
|
|
1314
|
+
/**
|
|
1315
|
+
* A new attempt starts from the file's state (so `expand`, `testPath` and keys a `beforeAll` set
|
|
1316
|
+
* carry over) with fresh counters and its own name. Keys a test sets with `expect.setState` stay
|
|
1317
|
+
* in that attempt: Jest's one shared object would carry them to the tests after it (B08 notes).
|
|
1318
|
+
*/
|
|
1319
|
+
function newAttemptState(fileState, testId, test, nameSeparator) {
|
|
1320
|
+
const { expectedAssertionsNumberError: _number, isExpectingAssertionsError: _expecting, ...carried } = fileState;
|
|
1321
|
+
return {
|
|
1322
|
+
...carried,
|
|
1323
|
+
...freshCounters(),
|
|
1324
|
+
currentTestId: testId,
|
|
1325
|
+
...test === void 0 ? {} : {
|
|
1326
|
+
currentTestName: test.fullName.join(nameSeparator),
|
|
1327
|
+
currentTestPath: test.fullName,
|
|
1328
|
+
testFailing: test.expectFail
|
|
1329
|
+
}
|
|
1330
|
+
};
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
export { AsymmetricMatcher, ExpectError, MATCHERS_SLOT, MatcherResultError, createEndOfTest, createExpect, createMatcherRegistry, createStateSource, equalityTesters, installMatchersSlot, matcherCallStack, snapshotMatchers, snapshotRegistry };
|