@unrift/core 0.3.0 → 0.5.0
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/bin/unrift.mjs +2 -1
- package/dist/esm/cli.js +19 -1
- package/dist/esm/expect.d.ts +14 -0
- package/dist/esm/expect.d.ts.map +1 -1
- package/dist/esm/index.d.ts +3 -1
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +2 -0
- package/dist/esm/interface.d.ts +7 -3
- package/dist/esm/interface.d.ts.map +1 -1
- package/dist/esm/interface.js +9 -5
- package/dist/esm/matchers.d.ts.map +1 -1
- package/dist/esm/matchers.js +195 -1
- package/dist/esm/mock/auto.d.ts +27 -0
- package/dist/esm/mock/auto.d.ts.map +1 -0
- package/dist/esm/mock/auto.js +108 -0
- package/dist/esm/mock/fetch.d.ts +47 -0
- package/dist/esm/mock/fetch.d.ts.map +1 -0
- package/dist/esm/mock/fetch.js +149 -0
- package/dist/esm/mock/fs.d.ts +54 -0
- package/dist/esm/mock/fs.d.ts.map +1 -0
- package/dist/esm/mock/fs.js +125 -0
- package/dist/esm/mock/index.d.ts +70 -0
- package/dist/esm/mock/index.d.ts.map +1 -0
- package/dist/esm/mock/index.js +70 -0
- package/dist/esm/mock/module-loader.d.ts +66 -0
- package/dist/esm/mock/module-loader.d.ts.map +1 -0
- package/dist/esm/mock/module-loader.js +123 -0
- package/dist/esm/mock/module.d.ts +99 -0
- package/dist/esm/mock/module.d.ts.map +1 -0
- package/dist/esm/mock/module.js +198 -0
- package/dist/esm/mock/register-loader.d.ts +17 -0
- package/dist/esm/mock/register-loader.d.ts.map +1 -0
- package/dist/esm/mock/register-loader.js +45 -0
- package/dist/esm/mock/spy.d.ts +73 -0
- package/dist/esm/mock/spy.d.ts.map +1 -0
- package/dist/esm/mock/spy.js +307 -0
- package/dist/esm/mock/stub.d.ts +26 -0
- package/dist/esm/mock/stub.d.ts.map +1 -0
- package/dist/esm/mock/stub.js +82 -0
- package/dist/esm/mock/timers.d.ts +51 -0
- package/dist/esm/mock/timers.d.ts.map +1 -0
- package/dist/esm/mock/timers.js +581 -0
- package/dist/esm/run.d.ts +4 -7
- package/dist/esm/run.d.ts.map +1 -1
- package/dist/esm/run.js +6 -2
- package/dist/esm/runner.d.ts +1 -0
- package/dist/esm/runner.d.ts.map +1 -1
- package/dist/esm/runner.js +21 -10
- package/dist/esm/suite.d.ts +24 -6
- package/dist/esm/suite.d.ts.map +1 -1
- package/dist/esm/suite.js +114 -20
- package/dist/esm/test.d.ts +5 -1
- package/dist/esm/test.d.ts.map +1 -1
- package/dist/esm/test.js +20 -6
- package/dist/esm/utils/compareEngine.js +3 -3
- package/dist/esm/utils/defineConfig.d.ts +1 -0
- package/dist/esm/utils/defineConfig.d.ts.map +1 -1
- package/dist/esm/utils/discoverTestFiles.js +1 -1
- package/dist/esm/utils/helpers.d.ts +12 -0
- package/dist/esm/utils/helpers.d.ts.map +1 -1
- package/dist/esm/utils/helpers.js +20 -0
- package/dist/esm/utils/toThrow.d.ts.map +1 -1
- package/dist/esm/utils/toThrow.js +2 -1
- package/package.json +4 -3
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Spy / Mock function primitive.
|
|
3
|
+
*
|
|
4
|
+
* Both `spy()` and `mock.fn()` produce the same object - a callable that
|
|
5
|
+
* records every invocation, supports configurable implementations, and can
|
|
6
|
+
* be restored to the original (when created via `spyOn`).
|
|
7
|
+
*/
|
|
8
|
+
export const SPY_BRAND = Symbol.for("unrift.spy");
|
|
9
|
+
/**
|
|
10
|
+
* Internal registries. Used by `mock.clearAll()`, `mock.resetAll()`,
|
|
11
|
+
* and `mock.restoreAll()` to operate on every spy created so far.
|
|
12
|
+
*/
|
|
13
|
+
export const activeSpies = new Set();
|
|
14
|
+
export const activeRestorers = new Set();
|
|
15
|
+
/**
|
|
16
|
+
* Returns true if the value is a spy created by `spy()` or `spyOn()`.
|
|
17
|
+
* Used by mock matchers to validate their `received` argument.
|
|
18
|
+
*/
|
|
19
|
+
export function isSpy(value) {
|
|
20
|
+
return (typeof value === "function" &&
|
|
21
|
+
value[SPY_BRAND] === true);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* True if `fn` can be used with `new` / `Reflect.construct`. Arrow functions,
|
|
25
|
+
* object/class methods, async and generator functions, and most bound
|
|
26
|
+
* functions are NOT constructable.
|
|
27
|
+
*
|
|
28
|
+
* Probes by using `fn` as the `newTarget` of a no-op construct - this
|
|
29
|
+
* validates constructability without ever invoking `fn`'s body.
|
|
30
|
+
*/
|
|
31
|
+
function isConstructor(fn) {
|
|
32
|
+
try {
|
|
33
|
+
Reflect.construct(function () { }, [], fn);
|
|
34
|
+
return true;
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
function createSpy(config) {
|
|
41
|
+
let mockName = "spy";
|
|
42
|
+
let currentImpl = config.initialImpl;
|
|
43
|
+
const onceImpls = [];
|
|
44
|
+
const state = {
|
|
45
|
+
calls: [],
|
|
46
|
+
results: [],
|
|
47
|
+
contexts: [],
|
|
48
|
+
instances: [],
|
|
49
|
+
lastCall: undefined,
|
|
50
|
+
};
|
|
51
|
+
// The callable. Defined as a regular `function` (not arrow) so it has its own
|
|
52
|
+
// `this` binding when invoked as a method, and so `new spy(...)` works.
|
|
53
|
+
function spyImpl(...args) {
|
|
54
|
+
state.calls.push(args);
|
|
55
|
+
state.contexts.push(this);
|
|
56
|
+
state.lastCall = args;
|
|
57
|
+
/**
|
|
58
|
+
* Resolution order:
|
|
59
|
+
* 1. queued one-shot implementations (FIFO)
|
|
60
|
+
* 2. current permanent implementation
|
|
61
|
+
* 3. original (spyOn) implementation
|
|
62
|
+
* 4. no-op returning undefined
|
|
63
|
+
*/
|
|
64
|
+
const impl = onceImpls.shift() ?? currentImpl ?? config.originalImpl;
|
|
65
|
+
let isNewTarget = false;
|
|
66
|
+
try {
|
|
67
|
+
/**
|
|
68
|
+
* `new.target` would be cleaner, but inside this regular function we
|
|
69
|
+
* detect construction by checking whether `this` is an instance whose
|
|
70
|
+
* prototype matches the spy's prototype.
|
|
71
|
+
*/
|
|
72
|
+
isNewTarget =
|
|
73
|
+
new.target !== undefined ||
|
|
74
|
+
(this !== undefined &&
|
|
75
|
+
this !== null &&
|
|
76
|
+
Object.getPrototypeOf(this) === spyImpl.prototype);
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
isNewTarget = false;
|
|
80
|
+
}
|
|
81
|
+
try {
|
|
82
|
+
let value;
|
|
83
|
+
if (isNewTarget) {
|
|
84
|
+
// `new spy()` is always valid, regardless of the implementation.
|
|
85
|
+
if (impl && isConstructor(impl)) {
|
|
86
|
+
// Constructable impl: run it as the constructor with the spy's
|
|
87
|
+
// prototype (via newTarget), yielding its own instance.
|
|
88
|
+
value = Reflect.construct(impl, args, spyImpl);
|
|
89
|
+
}
|
|
90
|
+
else if (impl) {
|
|
91
|
+
// Non-constructable impl (arrow, method, async, …): can't
|
|
92
|
+
// Reflect.construct it. Run it against the object JS already created
|
|
93
|
+
// for us; the instance is that object, unless the impl explicitly
|
|
94
|
+
// returns one (constructor return semantics).
|
|
95
|
+
const ret = impl.apply(this, args);
|
|
96
|
+
value = typeof ret === "object" && ret !== null ? ret : this;
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
// No impl: the instance is the object JS created for `new spy()`.
|
|
100
|
+
value = this;
|
|
101
|
+
}
|
|
102
|
+
state.instances.push(value);
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
value = impl ? impl.apply(this, args) : undefined;
|
|
106
|
+
}
|
|
107
|
+
state.results.push({ type: "return", value });
|
|
108
|
+
return value;
|
|
109
|
+
}
|
|
110
|
+
catch (err) {
|
|
111
|
+
state.results.push({ type: "throw", value: err });
|
|
112
|
+
throw err;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
// Attach state + methods.
|
|
116
|
+
const spy = spyImpl;
|
|
117
|
+
Object.defineProperty(spy, SPY_BRAND, {
|
|
118
|
+
value: true,
|
|
119
|
+
enumerable: false,
|
|
120
|
+
configurable: false,
|
|
121
|
+
writable: false,
|
|
122
|
+
});
|
|
123
|
+
Object.defineProperty(spy, "mock", {
|
|
124
|
+
value: state,
|
|
125
|
+
enumerable: false,
|
|
126
|
+
configurable: true,
|
|
127
|
+
writable: true,
|
|
128
|
+
});
|
|
129
|
+
spy.mockName = (name) => {
|
|
130
|
+
mockName = name;
|
|
131
|
+
return spy;
|
|
132
|
+
};
|
|
133
|
+
spy.getMockName = () => mockName;
|
|
134
|
+
spy.mockImplementation = (impl) => {
|
|
135
|
+
currentImpl = impl;
|
|
136
|
+
return spy;
|
|
137
|
+
};
|
|
138
|
+
spy.mockImplementationOnce = (impl) => {
|
|
139
|
+
onceImpls.push(impl);
|
|
140
|
+
return spy;
|
|
141
|
+
};
|
|
142
|
+
spy.mockReturnValue = (value) => spy.mockImplementation((() => value));
|
|
143
|
+
spy.mockReturnValueOnce = (value) => spy.mockImplementationOnce((() => value));
|
|
144
|
+
spy.mockResolvedValue = (value) => spy.mockImplementation((() => Promise.resolve(value)));
|
|
145
|
+
spy.mockResolvedValueOnce = (value) => spy.mockImplementationOnce((() => Promise.resolve(value)));
|
|
146
|
+
spy.mockRejectedValue = (error) => spy.mockImplementation((() => Promise.reject(error)));
|
|
147
|
+
spy.mockRejectedValueOnce = (error) => spy.mockImplementationOnce((() => Promise.reject(error)));
|
|
148
|
+
spy.mockClear = () => {
|
|
149
|
+
state.calls.length = 0;
|
|
150
|
+
state.results.length = 0;
|
|
151
|
+
state.contexts.length = 0;
|
|
152
|
+
state.instances.length = 0;
|
|
153
|
+
state.lastCall = undefined;
|
|
154
|
+
return spy;
|
|
155
|
+
};
|
|
156
|
+
spy.mockReset = () => {
|
|
157
|
+
spy.mockClear();
|
|
158
|
+
currentImpl = undefined;
|
|
159
|
+
onceImpls.length = 0;
|
|
160
|
+
return spy;
|
|
161
|
+
};
|
|
162
|
+
spy.mockRestore = () => {
|
|
163
|
+
spy.mockReset();
|
|
164
|
+
if (config.restoreFn) {
|
|
165
|
+
config.restoreFn();
|
|
166
|
+
activeRestorers.delete(config.restoreFn);
|
|
167
|
+
}
|
|
168
|
+
activeSpies.delete(spy);
|
|
169
|
+
};
|
|
170
|
+
activeSpies.add(spy);
|
|
171
|
+
return spy;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Creates a standalone spy / mock function. Records every invocation and
|
|
175
|
+
* supports configurable behavior via `.mockReturnValue`, `.mockImplementation`, etc.
|
|
176
|
+
*/
|
|
177
|
+
export function spy(impl) {
|
|
178
|
+
return createSpy({ initialImpl: impl });
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Walks the prototype chain to find the descriptor for `key` - needed
|
|
182
|
+
* because accessor properties (getter/setter) usually live on a prototype,
|
|
183
|
+
* not on the instance itself.
|
|
184
|
+
*/
|
|
185
|
+
function findDescriptor(obj, key) {
|
|
186
|
+
let current = obj;
|
|
187
|
+
while (current !== null) {
|
|
188
|
+
const descriptor = Object.getOwnPropertyDescriptor(current, key);
|
|
189
|
+
if (descriptor)
|
|
190
|
+
return { host: current, descriptor };
|
|
191
|
+
current = Object.getPrototypeOf(current);
|
|
192
|
+
}
|
|
193
|
+
return undefined;
|
|
194
|
+
}
|
|
195
|
+
export function spyOn(obj, key, accessor) {
|
|
196
|
+
// Accessor (getter/setter) path - 3-arg form.
|
|
197
|
+
if (accessor === "get" || accessor === "set") {
|
|
198
|
+
const found = findDescriptor(obj, key);
|
|
199
|
+
if (!found) {
|
|
200
|
+
throw new Error(`spyOn() could not find property "${String(key)}" on the target or its prototype chain`);
|
|
201
|
+
}
|
|
202
|
+
const { host, descriptor } = found;
|
|
203
|
+
const original = descriptor[accessor];
|
|
204
|
+
// Repeat spyOn on an already-spied accessor returns the existing spy.
|
|
205
|
+
// Wrapping a spy in a spy would capture the first spy as the "original",
|
|
206
|
+
// and restoring would then put the first spy back instead of the real
|
|
207
|
+
// accessor - leaking a mock past restoreAll().
|
|
208
|
+
if (isSpy(original)) {
|
|
209
|
+
return original;
|
|
210
|
+
}
|
|
211
|
+
if (descriptor.configurable === false) {
|
|
212
|
+
throw new Error(`spyOn() cannot wrap non-configurable property "${String(key)}"`);
|
|
213
|
+
}
|
|
214
|
+
if (typeof original !== "function") {
|
|
215
|
+
throw new Error(`spyOn(..., "${accessor}") requires "${String(key)}" to have a ${accessor}ter`);
|
|
216
|
+
}
|
|
217
|
+
// If the spy is on a prototype, restoring needs to put back the
|
|
218
|
+
// *prototype's* descriptor at the *prototype* level - not on `obj`.
|
|
219
|
+
// Idempotent: a second run (mockRestore + restoreAll) is a no-op.
|
|
220
|
+
let restored = false;
|
|
221
|
+
const restore = () => {
|
|
222
|
+
if (restored)
|
|
223
|
+
return;
|
|
224
|
+
restored = true;
|
|
225
|
+
Object.defineProperty(host, key, descriptor);
|
|
226
|
+
};
|
|
227
|
+
const accessorSpy = createSpy({
|
|
228
|
+
originalImpl: original,
|
|
229
|
+
restoreFn: restore,
|
|
230
|
+
});
|
|
231
|
+
const newDescriptor = {
|
|
232
|
+
configurable: true,
|
|
233
|
+
enumerable: descriptor.enumerable,
|
|
234
|
+
[accessor]: accessorSpy,
|
|
235
|
+
};
|
|
236
|
+
// Preserve the other half of the pair (the unspied accessor stays put).
|
|
237
|
+
if (accessor === "get" && descriptor.set)
|
|
238
|
+
newDescriptor.set = descriptor.set;
|
|
239
|
+
if (accessor === "set" && descriptor.get)
|
|
240
|
+
newDescriptor.get = descriptor.get;
|
|
241
|
+
Object.defineProperty(host, key, newDescriptor);
|
|
242
|
+
activeRestorers.add(restore);
|
|
243
|
+
return accessorSpy;
|
|
244
|
+
}
|
|
245
|
+
// Method path - original 2-arg behavior.
|
|
246
|
+
const original = obj[key];
|
|
247
|
+
// Repeat spyOn on an already-spied method returns the existing spy rather
|
|
248
|
+
// than wrapping it. A spy-wrapping-a-spy would capture the first spy as its
|
|
249
|
+
// "original", so restore order could put the first spy back after the real
|
|
250
|
+
// method - leaking a mock past restoreAll().
|
|
251
|
+
if (isSpy(original)) {
|
|
252
|
+
return original;
|
|
253
|
+
}
|
|
254
|
+
if (typeof original !== "function") {
|
|
255
|
+
throw new Error(`spyOn() requires a function property; got ${typeof original} for key "${String(key)}"`);
|
|
256
|
+
}
|
|
257
|
+
const descriptor = Object.getOwnPropertyDescriptor(obj, key);
|
|
258
|
+
if (descriptor && descriptor.configurable === false) {
|
|
259
|
+
throw new Error(`spyOn() cannot wrap non-configurable property "${String(key)}"`);
|
|
260
|
+
}
|
|
261
|
+
// Idempotent: mockRestore() followed by restoreAll() must not re-apply.
|
|
262
|
+
let restored = false;
|
|
263
|
+
const restore = () => {
|
|
264
|
+
if (restored)
|
|
265
|
+
return;
|
|
266
|
+
restored = true;
|
|
267
|
+
if (descriptor) {
|
|
268
|
+
Object.defineProperty(obj, key, descriptor);
|
|
269
|
+
}
|
|
270
|
+
else {
|
|
271
|
+
delete obj[key];
|
|
272
|
+
}
|
|
273
|
+
};
|
|
274
|
+
const spy = createSpy({
|
|
275
|
+
originalImpl: original,
|
|
276
|
+
restoreFn: restore,
|
|
277
|
+
});
|
|
278
|
+
Object.defineProperty(obj, key, {
|
|
279
|
+
value: spy,
|
|
280
|
+
writable: true,
|
|
281
|
+
configurable: true,
|
|
282
|
+
enumerable: descriptor?.enumerable ?? true,
|
|
283
|
+
});
|
|
284
|
+
activeRestorers.add(restore);
|
|
285
|
+
return spy;
|
|
286
|
+
}
|
|
287
|
+
// Clear call history on every active spy. Implementations are preserved.
|
|
288
|
+
export function clearAllMocks() {
|
|
289
|
+
for (const spy of activeSpies)
|
|
290
|
+
spy.mockClear();
|
|
291
|
+
}
|
|
292
|
+
// Clear call history AND remove all configured implementations on every active spy.
|
|
293
|
+
export function resetAllMocks() {
|
|
294
|
+
for (const spy of activeSpies)
|
|
295
|
+
spy.mockReset();
|
|
296
|
+
}
|
|
297
|
+
// Restore originals for every spyOn / stub created so far, then clear all spy state.
|
|
298
|
+
export function restoreAllMocks() {
|
|
299
|
+
// Iterate over a snapshot - restorers mutate the set as they run.
|
|
300
|
+
for (const restore of [...activeRestorers]) {
|
|
301
|
+
restore();
|
|
302
|
+
activeRestorers.delete(restore);
|
|
303
|
+
}
|
|
304
|
+
for (const spy of [...activeSpies])
|
|
305
|
+
spy.mockReset();
|
|
306
|
+
activeSpies.clear();
|
|
307
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `mock.stub` - replace any property on any object (function or value),
|
|
3
|
+
* with restoration tracked centrally so `mock.restoreAll()` can undo it.
|
|
4
|
+
*
|
|
5
|
+
* Use `spyOn` when you want a wrapped function spy. Use `stub` when you
|
|
6
|
+
* want to swap in a fixed value or non-function replacement.
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Replace `target[key]` with `value`. Returns a function that restores
|
|
10
|
+
* the original property descriptor (or removes the key entirely if it
|
|
11
|
+
* didn't exist before).
|
|
12
|
+
*
|
|
13
|
+
* Stubbing the same property again before restoring updates the value but
|
|
14
|
+
* keeps the first stub's original - so restore always yields the real value,
|
|
15
|
+
* no matter how many times the property was re-stubbed.
|
|
16
|
+
*
|
|
17
|
+
* The restorer is also registered with the global `mock.restoreAll()`
|
|
18
|
+
* pool, so test cleanup can reset every stub at once.
|
|
19
|
+
*/
|
|
20
|
+
export declare function stub<T extends object, K extends keyof T>(target: T, key: K, value: T[K]): () => void;
|
|
21
|
+
/**
|
|
22
|
+
* Convenience wrapper: `mock.stub(globalThis, key, value)`. Useful for
|
|
23
|
+
* swapping `fetch`, `crypto`, `console`, etc. during a test.
|
|
24
|
+
*/
|
|
25
|
+
export declare function mockGlobal<K extends string>(key: K, value: unknown): () => void;
|
|
26
|
+
//# sourceMappingURL=stub.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stub.d.ts","sourceRoot":"","sources":["../../../src/mock/stub.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAYH;;;;;;;;;;;GAWG;AACH,wBAAgB,IAAI,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,MAAM,CAAC,EACtD,MAAM,EAAE,CAAC,EACT,GAAG,EAAE,CAAC,EACN,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,GACV,MAAM,IAAI,CAuDZ;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,CAAC,SAAS,MAAM,EACzC,GAAG,EAAE,CAAC,EACN,KAAK,EAAE,OAAO,GACb,MAAM,IAAI,CAEZ"}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `mock.stub` - replace any property on any object (function or value),
|
|
3
|
+
* with restoration tracked centrally so `mock.restoreAll()` can undo it.
|
|
4
|
+
*
|
|
5
|
+
* Use `spyOn` when you want a wrapped function spy. Use `stub` when you
|
|
6
|
+
* want to swap in a fixed value or non-function replacement.
|
|
7
|
+
*/
|
|
8
|
+
import { activeRestorers } from "./spy.js";
|
|
9
|
+
/**
|
|
10
|
+
* Tracks live stubs per target so a repeat `stub()` on the same (target, key)
|
|
11
|
+
* updates the value in place and returns the ORIGINAL restore. Without this,
|
|
12
|
+
* the second stub would capture the first stub's value as its "original" and
|
|
13
|
+
* restoring would leave the first stub in place instead of the real value.
|
|
14
|
+
*/
|
|
15
|
+
const activeStubs = new WeakMap();
|
|
16
|
+
/**
|
|
17
|
+
* Replace `target[key]` with `value`. Returns a function that restores
|
|
18
|
+
* the original property descriptor (or removes the key entirely if it
|
|
19
|
+
* didn't exist before).
|
|
20
|
+
*
|
|
21
|
+
* Stubbing the same property again before restoring updates the value but
|
|
22
|
+
* keeps the first stub's original - so restore always yields the real value,
|
|
23
|
+
* no matter how many times the property was re-stubbed.
|
|
24
|
+
*
|
|
25
|
+
* The restorer is also registered with the global `mock.restoreAll()`
|
|
26
|
+
* pool, so test cleanup can reset every stub at once.
|
|
27
|
+
*/
|
|
28
|
+
export function stub(target, key, value) {
|
|
29
|
+
// Repeat stub on a live-stubbed key: swap the value, reuse the original
|
|
30
|
+
// descriptor captured by the first stub.
|
|
31
|
+
const existing = activeStubs.get(target)?.get(key);
|
|
32
|
+
if (existing) {
|
|
33
|
+
Object.defineProperty(target, key, {
|
|
34
|
+
value,
|
|
35
|
+
writable: true,
|
|
36
|
+
configurable: true,
|
|
37
|
+
enumerable: Object.getOwnPropertyDescriptor(target, key)?.enumerable,
|
|
38
|
+
});
|
|
39
|
+
return existing;
|
|
40
|
+
}
|
|
41
|
+
const original = Object.getOwnPropertyDescriptor(target, key);
|
|
42
|
+
const hadOwn = original !== undefined;
|
|
43
|
+
if (original && original.configurable === false) {
|
|
44
|
+
throw new Error(`mock.stub() cannot replace non-configurable property "${String(key)}"`);
|
|
45
|
+
}
|
|
46
|
+
Object.defineProperty(target, key, {
|
|
47
|
+
value,
|
|
48
|
+
writable: true,
|
|
49
|
+
configurable: true,
|
|
50
|
+
enumerable: original?.enumerable ?? true,
|
|
51
|
+
});
|
|
52
|
+
let restored = false;
|
|
53
|
+
const restore = () => {
|
|
54
|
+
if (restored)
|
|
55
|
+
return;
|
|
56
|
+
restored = true;
|
|
57
|
+
if (hadOwn && original) {
|
|
58
|
+
Object.defineProperty(target, key, original);
|
|
59
|
+
}
|
|
60
|
+
else {
|
|
61
|
+
// Property didn't exist on this object before, remove it to restore original behavior, including prototype inheritance.
|
|
62
|
+
delete target[key];
|
|
63
|
+
}
|
|
64
|
+
activeStubs.get(target)?.delete(key);
|
|
65
|
+
activeRestorers.delete(restore);
|
|
66
|
+
};
|
|
67
|
+
let byKey = activeStubs.get(target);
|
|
68
|
+
if (!byKey) {
|
|
69
|
+
byKey = new Map();
|
|
70
|
+
activeStubs.set(target, byKey);
|
|
71
|
+
}
|
|
72
|
+
byKey.set(key, restore);
|
|
73
|
+
activeRestorers.add(restore);
|
|
74
|
+
return restore;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Convenience wrapper: `mock.stub(globalThis, key, value)`. Useful for
|
|
78
|
+
* swapping `fetch`, `crypto`, `console`, etc. during a test.
|
|
79
|
+
*/
|
|
80
|
+
export function mockGlobal(key, value) {
|
|
81
|
+
return stub(globalThis, key, value);
|
|
82
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fake clock - controllable replacements for `setTimeout`, `setInterval`,
|
|
3
|
+
* `setImmediate`, `process.nextTick`, `queueMicrotask`, `Date`, `Date.now`,
|
|
4
|
+
* and `performance.now`.
|
|
5
|
+
*
|
|
6
|
+
* Tests opt in via `mock.useFakeTimers()` and drain queued tasks deterministically
|
|
7
|
+
* with `advanceTimersByTime(ms)` / `runAllTimers()` / `runOnlyPendingTimers()`.
|
|
8
|
+
*
|
|
9
|
+
* Restoration:
|
|
10
|
+
* - `mock.useRealTimers()` reverts every patched global to its original
|
|
11
|
+
* - `mock.restoreAll()` does the same as part of bulk cleanup
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Names of host APIs that `useFakeTimers` can patch. `setTimeout` implicitly
|
|
15
|
+
* pairs with `clearTimeout`, `setInterval` with `clearInterval`, and
|
|
16
|
+
* `setImmediate` with `clearImmediate` - you can't fake one half of a pair
|
|
17
|
+
* without breaking the other.
|
|
18
|
+
*/
|
|
19
|
+
export type FakeableApi = "setTimeout" | "setInterval" | "setImmediate" | "queueMicrotask" | "process.nextTick" | "Date" | "performance";
|
|
20
|
+
export interface UseFakeTimersOptions {
|
|
21
|
+
now?: Date | string | number;
|
|
22
|
+
/**
|
|
23
|
+
* Opt-in: only the listed APIs are faked; everything else stays real.
|
|
24
|
+
* Mutually exclusive with `doNotFake`.
|
|
25
|
+
*/
|
|
26
|
+
toFake?: readonly FakeableApi[];
|
|
27
|
+
/**
|
|
28
|
+
* Opt-out: everything is faked except the listed APIs.
|
|
29
|
+
* Mutually exclusive with `toFake`.
|
|
30
|
+
*/
|
|
31
|
+
doNotFake?: readonly FakeableApi[];
|
|
32
|
+
}
|
|
33
|
+
export declare function useFakeTimers(options?: UseFakeTimersOptions): void;
|
|
34
|
+
export declare function useRealTimers(): void;
|
|
35
|
+
export declare function advanceTimersByTime(ms: number): void;
|
|
36
|
+
export declare function runAllTimers(): void;
|
|
37
|
+
export declare function runOnlyPendingTimers(): void;
|
|
38
|
+
/**
|
|
39
|
+
* Like `advanceTimersByTime`, but awaits Promise return values from
|
|
40
|
+
* timer callbacks and yields to microtasks between pumps. Use this when
|
|
41
|
+
* the code under test does `await` work inside a `setTimeout` callback.
|
|
42
|
+
*/
|
|
43
|
+
export declare function advanceTimersByTimeAsync(ms: number): Promise<void>;
|
|
44
|
+
/** Async sibling of `runAllTimers`. */
|
|
45
|
+
export declare function runAllTimersAsync(): Promise<void>;
|
|
46
|
+
/** Async sibling of `runOnlyPendingTimers`. */
|
|
47
|
+
export declare function runOnlyPendingTimersAsync(): Promise<void>;
|
|
48
|
+
export declare function getTimerCount(): number;
|
|
49
|
+
export declare function setSystemTime(value: Date | string | number): void;
|
|
50
|
+
export declare function getRealSystemTime(): number;
|
|
51
|
+
//# sourceMappingURL=timers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"timers.d.ts","sourceRoot":"","sources":["../../../src/mock/timers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AA2PH;;;;;GAKG;AACH,MAAM,MAAM,WAAW,GACnB,YAAY,GACZ,aAAa,GACb,cAAc,GACd,gBAAgB,GAChB,kBAAkB,GAClB,MAAM,GACN,aAAa,CAAC;AAYlB,MAAM,WAAW,oBAAoB;IAEnC,GAAG,CAAC,EAAE,IAAI,GAAG,MAAM,GAAG,MAAM,CAAC;IAC7B;;;OAGG;IACH,MAAM,CAAC,EAAE,SAAS,WAAW,EAAE,CAAC;IAChC;;;OAGG;IACH,SAAS,CAAC,EAAE,SAAS,WAAW,EAAE,CAAC;CACpC;AAmGD,wBAAgB,aAAa,CAAC,OAAO,GAAE,oBAAyB,GAAG,IAAI,CA4GtE;AAED,wBAAgB,aAAa,IAAI,IAAI,CA4CpC;AAED,wBAAgB,mBAAmB,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,CAGpD;AAED,wBAAgB,YAAY,IAAI,IAAI,CAcnC;AAED,wBAAgB,oBAAoB,IAAI,IAAI,CAqB3C;AA4CD;;;;GAIG;AACH,wBAAsB,wBAAwB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAiBxE;AAED,uCAAuC;AACvC,wBAAsB,iBAAiB,IAAI,OAAO,CAAC,IAAI,CAAC,CAcvD;AAED,+CAA+C;AAC/C,wBAAsB,yBAAyB,IAAI,OAAO,CAAC,IAAI,CAAC,CAkB/D;AAED,wBAAgB,aAAa,IAAI,MAAM,CAKtC;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,IAAI,GAAG,MAAM,GAAG,MAAM,GAAG,IAAI,CAGjE;AAED,wBAAgB,iBAAiB,IAAI,MAAM,CAE1C"}
|