UNPKG

74.9 kBTypeScriptView Raw
1import * as FakeTimers from "@sinonjs/fake-timers";
2
3// sinon uses DOM dependencies which are absent in browser-less environment like node.js
4// to avoid compiler errors this monkey patch is used
5// see more details in https://github.com/DefinitelyTyped/DefinitelyTyped/issues/11351
6interface Event {} // eslint-disable-line @typescript-eslint/no-empty-interface
7interface Document {} // eslint-disable-line @typescript-eslint/no-empty-interface
8
9declare namespace Sinon {
10 type MatchPartialArguments<T> = {
11 [K in keyof T]?: SinonMatcher | (T[K] extends object ? MatchPartialArguments<T[K]> : T[K]);
12 };
13 // TODO: Alias for backward compatibility, remove on next major release
14 type DeepPartialOrMatcher<T> = MatchPartialArguments<T>;
15
16 type MatchExactArguments<T> = {
17 [K in keyof T]: SinonMatcher | (T[K] extends object ? MatchExactArguments<T[K]> : T[K]);
18 };
19 // TODO: Alias for backward compatibility, remove on next major release
20 type MatchArguments<T> = MatchExactArguments<T>;
21
22 interface SinonSpyCallApi<TArgs extends readonly any[] = any[], TReturnValue = any> {
23 // Properties
24 /**
25 * Array of received arguments.
26 */
27 args: TArgs;
28
29 // Methods
30 /**
31 * Returns true if the spy was called at least once with @param obj as this.
32 * calledOn also accepts a matcher spyCall.calledOn(sinon.match(fn)) (see matchers).
33 * @param obj
34 */
35 calledOn(obj: any): boolean;
36 /**
37 * Returns true if spy was called at least once with the provided arguments.
38 * Can be used for partial matching, Sinon only checks the provided arguments against actual arguments,
39 * so a call that received the provided arguments (in the same spots) and possibly others as well will return true.
40 * @param args
41 */
42 calledWith(...args: MatchPartialArguments<TArgs>): boolean;
43 /**
44 * Returns true if spy was called at least once with the provided arguments and no others.
45 */
46 calledWithExactly(...args: MatchExactArguments<TArgs>): boolean;
47 /**
48 * Returns true if spy/stub was called the new operator.
49 * Beware that this is inferred based on the value of the this object and the spy function’s prototype,
50 * so it may give false positives if you actively return the right kind of object.
51 */
52 calledWithNew(): boolean;
53 /**
54 * Returns true if spy was called at exactly once with the provided arguments.
55 * @param args
56 */
57 calledOnceWith(...args: MatchPartialArguments<TArgs>): boolean;
58 calledOnceWithExactly(...args: MatchExactArguments<TArgs>): boolean;
59 /**
60 * Returns true if spy was called with matching arguments (and possibly others).
61 * This behaves the same as spy.calledWith(sinon.match(arg1), sinon.match(arg2), ...).
62 * @param args
63 */
64 calledWithMatch(...args: MatchPartialArguments<TArgs>): boolean;
65 /**
66 * Returns true if call did not receive provided arguments.
67 * @param args
68 */
69 notCalledWith(...args: MatchExactArguments<TArgs>): boolean;
70 /**
71 * Returns true if call did not receive matching arguments.
72 * This behaves the same as spyCall.notCalledWith(sinon.match(arg1), sinon.match(arg2), ...).
73 * @param args
74 */
75 notCalledWithMatch(...args: MatchPartialArguments<TArgs>): boolean;
76 /**
77 * Returns true if spy returned the provided value at least once.
78 * Uses deep comparison for objects and arrays. Use spy.returned(sinon.match.same(obj)) for strict comparison (see matchers).
79 * @param value
80 */
81 returned(value: TReturnValue | SinonMatcher): boolean;
82 /**
83 * Returns true if spy threw an exception at least once.
84 */
85 threw(): boolean;
86 /**
87 * Returns true if spy threw an exception of the provided type at least once.
88 */
89 threw(type: string): boolean;
90 /**
91 * Returns true if spy threw the provided exception object at least once.
92 */
93 threw(obj: any): boolean;
94 /**
95 * Like yield, but with an explicit argument number specifying which callback to call.
96 * Useful if a function is called with more than one callback, and simply calling the first callback is not desired.
97 * @param pos
98 */
99 callArg(pos: number): unknown[];
100 callArgOn(pos: number, obj: any, ...args: any[]): unknown[];
101 /**
102 * Like callArg, but with arguments.
103 */
104 callArgWith(pos: number, ...args: any[]): unknown[];
105 callArgOnWith(pos: number, obj: any, ...args: any[]): unknown[];
106 /**
107 * Invoke callbacks passed to the stub with the given arguments.
108 * If the stub was never called with a function argument, yield throws an error.
109 * Returns an Array with all callbacks return values in the order they were called, if no error is thrown.
110 * Also aliased as invokeCallback.
111 */
112 yield(...args: any[]): unknown[];
113 yieldOn(obj: any, ...args: any[]): unknown[];
114 /**
115 * Invokes callbacks passed as a property of an object to the stub.
116 * Like yield, yieldTo grabs the first matching argument, finds the callback and calls it with the (optional) arguments.
117 */
118 yieldTo(property: string, ...args: any[]): unknown[];
119 yieldToOn(property: string, obj: any, ...args: any[]): unknown[];
120 }
121
122 interface SinonSpyCall<TArgs extends readonly any[] = any[], TReturnValue = any>
123 extends SinonSpyCallApi<TArgs, TReturnValue>
124 {
125 /**
126 * The call’s this value.
127 */
128 thisValue: any;
129 /**
130 * Exception thrown, if any.
131 */
132 exception: any;
133 /**
134 * Return value.
135 */
136 returnValue: TReturnValue;
137 /**
138 * This property is a convenience for a call’s callback.
139 * When the last argument in a call is a Function, then callback will reference that. Otherwise it will be undefined.
140 */
141 callback: Function | undefined;
142
143 /**
144 * This property is a convenience for the first argument of the call.
145 */
146 firstArg: any;
147
148 /**
149 * This property is a convenience for the last argument of the call.
150 */
151 lastArg: any;
152
153 /**
154 * Returns true if the spy call occurred before another spy call.
155 * @param call
156 */
157 calledBefore(call: SinonSpyCall<any>): boolean;
158 /**
159 * Returns true if the spy call occurred after another spy call.
160 * @param call
161 */
162 calledAfter(call: SinonSpyCall<any>): boolean;
163 }
164
165 interface SinonSpy<TArgs extends readonly any[] = any[], TReturnValue = any> extends
166 Pick<
167 SinonSpyCallApi<TArgs, TReturnValue>,
168 Exclude<keyof SinonSpyCallApi<TArgs, TReturnValue>, "args">
169 >
170 {
171 // Properties
172 /**
173 * The number of recorded calls.
174 */
175 callCount: number;
176 /**
177 * true if the spy was called at least once
178 */
179 called: boolean;
180 /**
181 * true if the spy was not called
182 */
183 notCalled: boolean;
184 /**
185 * true if spy was called exactly once
186 */
187 calledOnce: boolean;
188 /**
189 * true if the spy was called exactly twice
190 */
191 calledTwice: boolean;
192 /**
193 * true if the spy was called exactly thrice
194 */
195 calledThrice: boolean;
196 /**
197 * The first call
198 */
199 firstCall: SinonSpyCall<TArgs, TReturnValue>;
200 /**
201 * The second call
202 */
203 secondCall: SinonSpyCall<TArgs, TReturnValue>;
204 /**
205 * The third call
206 */
207 thirdCall: SinonSpyCall<TArgs, TReturnValue>;
208 /**
209 * The last call
210 */
211 lastCall: SinonSpyCall<TArgs, TReturnValue>;
212 /**
213 * Array of this objects, spy.thisValues[0] is the this object for the first call.
214 */
215 thisValues: any[];
216 /**
217 * Array of arguments received, spy.args[0] is an array of arguments received in the first call.
218 */
219 args: TArgs[];
220 /**
221 * Array of exception objects thrown, spy.exceptions[0] is the exception thrown by the first call.
222 * If the call did not throw an error, the value at the call’s location in .exceptions will be undefined.
223 */
224 exceptions: any[];
225 /**
226 * Array of return values, spy.returnValues[0] is the return value of the first call.
227 * If the call did not explicitly return a value, the value at the call’s location in .returnValues will be undefined.
228 */
229 returnValues: TReturnValue[];
230
231 /**
232 * Holds a reference to the original method/function this stub has wrapped.
233 */
234 wrappedMethod: (...args: TArgs) => TReturnValue;
235
236 // Methods
237 (...args: TArgs): TReturnValue;
238
239 /**
240 * Returns true if the spy was called before @param anotherSpy
241 * @param anotherSpy
242 */
243 calledBefore(anotherSpy: SinonSpy<any>): boolean;
244 /**
245 * Returns true if the spy was called after @param anotherSpy
246 * @param anotherSpy
247 */
248 calledAfter(anotherSpy: SinonSpy<any>): boolean;
249 /**
250 * Returns true if spy was called before @param anotherSpy, and no spy calls occurred between spy and @param anotherSpy.
251 * @param anotherSpy
252 */
253 calledImmediatelyBefore(anotherSpy: SinonSpy<any>): boolean;
254 /**
255 * Returns true if spy was called after @param anotherSpy, and no spy calls occurred between @param anotherSpy and spy.
256 * @param anotherSpy
257 */
258 calledImmediatelyAfter(anotherSpy: SinonSpy<any>): boolean;
259
260 /**
261 * Creates a spy that only records calls when the received arguments match those passed to withArgs.
262 * This is useful to be more expressive in your assertions, where you can access the spy with the same call.
263 * @param args Expected args
264 */
265 withArgs(...args: MatchPartialArguments<TArgs>): SinonSpy<TArgs, TReturnValue>;
266 /**
267 * Returns true if the spy was always called with @param obj as this.
268 * @param obj
269 */
270 alwaysCalledOn(obj: any): boolean;
271 /**
272 * Returns true if spy was always called with the provided arguments (and possibly others).
273 */
274 alwaysCalledWith(...args: MatchExactArguments<TArgs>): boolean;
275 /**
276 * Returns true if spy was always called with the exact provided arguments.
277 * @param args
278 */
279 alwaysCalledWithExactly(...args: MatchExactArguments<TArgs>): boolean;
280 /**
281 * Returns true if spy was always called with matching arguments (and possibly others).
282 * This behaves the same as spy.alwaysCalledWith(sinon.match(arg1), sinon.match(arg2), ...).
283 * @param args
284 */
285 alwaysCalledWithMatch(...args: TArgs): boolean;
286 /**
287 * Returns true if the spy/stub was never called with the provided arguments.
288 * @param args
289 */
290 neverCalledWith(...args: MatchExactArguments<TArgs>): boolean;
291 /**
292 * Returns true if the spy/stub was never called with matching arguments.
293 * This behaves the same as spy.neverCalledWith(sinon.match(arg1), sinon.match(arg2), ...).
294 * @param args
295 */
296 neverCalledWithMatch(...args: TArgs): boolean;
297 /**
298 * Returns true if spy always threw an exception.
299 */
300 alwaysThrew(): boolean;
301 /**
302 * Returns true if spy always threw an exception of the provided type.
303 */
304 alwaysThrew(type: string): boolean;
305 /**
306 * Returns true if spy always threw the provided exception object.
307 */
308 alwaysThrew(obj: any): boolean;
309 /**
310 * Returns true if spy always returned the provided value.
311 * @param obj
312 */
313 alwaysReturned(obj: any): boolean;
314 /**
315 * Invoke callbacks passed to the stub with the given arguments.
316 * If the stub was never called with a function argument, yield throws an error.
317 * Returns an Array with all callbacks return values in the order they were called, if no error is thrown.
318 */
319 invokeCallback(...args: TArgs): void;
320 /**
321 * Set the displayName of the spy or stub.
322 * @param name
323 */
324 named(name: string): SinonSpy<TArgs, TReturnValue>;
325 /**
326 * Returns the nth call.
327 * Accessing individual calls helps with more detailed behavior verification when the spy is called more than once.
328 * @param n Zero-based index of the spy call.
329 */
330 getCall(n: number): SinonSpyCall<TArgs, TReturnValue>;
331 /**
332 * Returns an Array of all calls recorded by the spy.
333 */
334 getCalls(): Array<SinonSpyCall<TArgs, TReturnValue>>;
335 /**
336 * Resets the state of a spy.
337 */
338 resetHistory(): void;
339 /**
340 * Returns the passed format string with the following replacements performed:
341 * * %n - the name of the spy "spy" by default)
342 * * %c - the number of times the spy was called, in words ("once", "twice", etc.)
343 * * %C - a list of string representations of the calls to the spy, with each call prefixed by a newline and four spaces
344 * * %t - a comma-delimited list of this values the spy was called on
345 * * %n - the formatted value of the nth argument passed to printf
346 * * %* - a comma-delimited list of the (non-format string) arguments passed to printf
347 * * %D - a multi-line list of the arguments received by all calls to the spy
348 * @param format
349 * @param args
350 */
351 printf(format: string, ...args: any[]): string;
352 /**
353 * Replaces the spy with the original method. Only available if the spy replaced an existing method.
354 */
355 restore(): void;
356 }
357
358 interface SinonSpyStatic {
359 /**
360 * Creates an anonymous function that records arguments, this value, exceptions and return values for all calls.
361 */
362 (): SinonSpy;
363 /**
364 * Spies on the provided function
365 */
366 <F extends (...args: any[]) => any>(func: F): SinonSpy<Parameters<F>, ReturnType<F>>;
367 /**
368 * Spies on all the object’s methods.
369 */
370 <T>(obj: T): SinonSpiedInstance<T>;
371 /**
372 * Creates a spy for object.method and replaces the original method with the spy.
373 * An exception is thrown if the property is not already a function.
374 * The spy acts exactly like the original method in all cases.
375 * The original method can be restored by calling object.method.restore().
376 * The returned spy is the function object which replaced the original method. spy === object.method.
377 */
378 <T, K extends keyof T>(
379 obj: T,
380 method: K,
381 ): T[K] extends (...args: infer TArgs) => infer TReturnValue ? SinonSpy<TArgs, TReturnValue>
382 : SinonSpy;
383
384 <T, K extends keyof T>(obj: T, method: K, types: Array<"get" | "set">): PropertyDescriptor & {
385 get: SinonSpy<[], T[K]>;
386 set: SinonSpy<[T[K]], void>;
387 };
388 }
389
390 type SinonSpiedInstance<T> = {
391 [P in keyof T]: SinonSpiedMember<T[P]>;
392 };
393
394 type SinonSpiedMember<T> = T extends (...args: infer TArgs) => infer TReturnValue ? SinonSpy<TArgs, TReturnValue>
395 : T;
396
397 interface SinonStub<TArgs extends readonly any[] = any[], TReturnValue = any>
398 extends SinonSpy<TArgs, TReturnValue>
399 {
400 /**
401 * Resets the stub’s behaviour to the default behaviour
402 * You can reset behaviour of all stubs using sinon.resetBehavior()
403 */
404 resetBehavior(): void;
405 /**
406 * Resets both behaviour and history of the stub.
407 * This is equivalent to calling both stub.resetBehavior() and stub.resetHistory()
408 * Updated in sinon@2.0.0
409 * Since sinon@5.0.0
410 * As a convenience, you can apply stub.reset() to all stubs using sinon.reset()
411 */
412 reset(): void;
413 /**
414 * Causes the stub to return promises using a specific Promise library instead of the global one when using stub.rejects or stub.resolves.
415 * Returns the stub to allow chaining.
416 */
417 usingPromise(promiseLibrary: any): SinonStub<TArgs, TReturnValue>;
418
419 /**
420 * Makes the stub return the provided @param obj value.
421 * @param obj
422 */
423 returns(obj: TReturnValue): SinonStub<TArgs, TReturnValue>;
424 /**
425 * Causes the stub to return the argument at the provided @param index.
426 * stub.returnsArg(0); causes the stub to return the first argument.
427 * If the argument at the provided index is not available, prior to sinon@6.1.2, an undefined value will be returned;
428 * starting from sinon@6.1.2, a TypeError will be thrown.
429 * @param index
430 */
431 returnsArg(index: number): SinonStub<TArgs, TReturnValue>;
432 /**
433 * Causes the stub to return its this value.
434 * Useful for stubbing jQuery-style fluent APIs.
435 */
436 returnsThis(): SinonStub<TArgs, TReturnValue>;
437 /**
438 * Causes the stub to return a Promise which resolves to the provided value.
439 * When constructing the Promise, sinon uses the Promise.resolve method.
440 * You are responsible for providing a polyfill in environments which do not provide Promise.
441 * The Promise library can be overwritten using the usingPromise method.
442 * Since sinon@2.0.0
443 */
444 resolves(
445 value?: TReturnValue extends PromiseLike<infer TResolveValue> ? TResolveValue : any,
446 ): SinonStub<TArgs, TReturnValue>;
447 /**
448 * Causes the stub to return a Promise which resolves to the argument at the provided index.
449 * stub.resolvesArg(0); causes the stub to return a Promise which resolves to the first argument.
450 * If the argument at the provided index is not available, a TypeError will be thrown.
451 */
452 resolvesArg(index: number): SinonStub<TArgs, TReturnValue>;
453 /**
454 * Causes the stub to return a Promise which resolves to its this value.
455 */
456 resolvesThis(): SinonStub<TArgs, TReturnValue>;
457 /**
458 * Causes the stub to throw an exception (Error).
459 * @param type
460 */
461 throws(type?: string): SinonStub<TArgs, TReturnValue>;
462 /**
463 * Causes the stub to throw the provided exception object.
464 */
465 throws(obj: any): SinonStub<TArgs, TReturnValue>;
466 /**
467 * Causes the stub to throw the argument at the provided index.
468 * stub.throwsArg(0); causes the stub to throw the first argument as the exception.
469 * If the argument at the provided index is not available, a TypeError will be thrown.
470 * Since sinon@2.3.0
471 * @param index
472 */
473 throwsArg(index: number): SinonStub<TArgs, TReturnValue>;
474 throwsException(type?: string): SinonStub<TArgs, TReturnValue>;
475 throwsException(obj: any): SinonStub<TArgs, TReturnValue>;
476 /**
477 * Causes the stub to return a Promise which rejects with an exception (Error).
478 * When constructing the Promise, sinon uses the Promise.reject method.
479 * You are responsible for providing a polyfill in environments which do not provide Promise.
480 * The Promise library can be overwritten using the usingPromise method.
481 * Since sinon@2.0.0
482 */
483 rejects(): SinonStub<TArgs, TReturnValue>;
484 /**
485 * Causes the stub to return a Promise which rejects with an exception of the provided type.
486 * Since sinon@2.0.0
487 */
488 rejects(errorType: string): SinonStub<TArgs, TReturnValue>;
489 /**
490 * Causes the stub to return a Promise which rejects with the provided exception object.
491 * Since sinon@2.0.0
492 */
493 rejects(value: any): SinonStub<TArgs, TReturnValue>;
494 /**
495 * Causes the stub to call the argument at the provided index as a callback function.
496 * stub.callsArg(0); causes the stub to call the first argument as a callback.
497 * If the argument at the provided index is not available or is not a function, a TypeError will be thrown.
498 */
499 callsArg(index: number): SinonStub<TArgs, TReturnValue>;
500 /**
501 * Causes the original method wrapped into the stub to be called when none of the conditional stubs are matched.
502 */
503 callThrough(): SinonStub<TArgs, TReturnValue>;
504 /**
505 * Like stub.callsArg(index); but with an additional parameter to pass the this context.
506 * @param index
507 * @param context
508 */
509 callsArgOn(index: number, context: any): SinonStub<TArgs, TReturnValue>;
510 /**
511 * Like callsArg, but with arguments to pass to the callback.
512 * @param index
513 * @param args
514 */
515 callsArgWith(index: number, ...args: any[]): SinonStub<TArgs, TReturnValue>;
516 /**
517 * Like above but with an additional parameter to pass the this context.
518 * @param index
519 * @param context
520 * @param args
521 */
522 callsArgOnWith(index: number, context: any, ...args: any[]): SinonStub<TArgs, TReturnValue>;
523 /**
524 * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed.
525 * In Node environment the callback is deferred with process.nextTick.
526 * In a browser the callback is deferred with setTimeout(callback, 0).
527 * @param index
528 */
529 callsArgAsync(index: number): SinonStub<TArgs, TReturnValue>;
530 /**
531 * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed.
532 * In Node environment the callback is deferred with process.nextTick.
533 * In a browser the callback is deferred with setTimeout(callback, 0).
534 * @param index
535 * @param context
536 */
537 callsArgOnAsync(index: number, context: any): SinonStub<TArgs, TReturnValue>;
538 /**
539 * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed.
540 * In Node environment the callback is deferred with process.nextTick.
541 * In a browser the callback is deferred with setTimeout(callback, 0).
542 */
543 callsArgWithAsync(index: number, ...args: any[]): SinonStub<TArgs, TReturnValue>;
544 /**
545 * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed.
546 * In Node environment the callback is deferred with process.nextTick.
547 * In a browser the callback is deferred with setTimeout(callback, 0).
548 */
549 callsArgOnWithAsync(index: number, context: any, ...args: any[]): SinonStub<TArgs, TReturnValue>;
550 /**
551 * Makes the stub call the provided @param func when invoked.
552 * @param func
553 */
554 callsFake(func: (...args: TArgs) => TReturnValue): SinonStub<TArgs, TReturnValue>;
555 /**
556 * Replaces a new getter for this stub.
557 */
558 get(func: () => any): SinonStub<TArgs, TReturnValue>;
559 /**
560 * Defines a new setter for this stub.
561 * @param func
562 */
563 set(func: (v: any) => void): SinonStub<TArgs, TReturnValue>;
564 /**
565 * Defines the behavior of the stub on the @param n call. Useful for testing sequential interactions.
566 * There are methods onFirstCall, onSecondCall,onThirdCall to make stub definitions read more naturally.
567 * onCall can be combined with all of the behavior defining methods in this section. In particular, it can be used together with withArgs.
568 * @param n Zero-based index of the spy call.
569 */
570 onCall(n: number): SinonStub<TArgs, TReturnValue>;
571 /**
572 * Alias for stub.onCall(0);
573 */
574 onFirstCall(): SinonStub<TArgs, TReturnValue>;
575 /**
576 * Alias for stub.onCall(1);
577 */
578 onSecondCall(): SinonStub<TArgs, TReturnValue>;
579 /**
580 * Alias for stub.onCall(2);
581 */
582 onThirdCall(): SinonStub<TArgs, TReturnValue>;
583 /**
584 * Defines a new value for this stub.
585 * @param val
586 */
587 value(val: any): SinonStub<TArgs, TReturnValue>;
588 /**
589 * Set the displayName of the spy or stub.
590 * @param name
591 */
592 named(name: string): SinonStub<TArgs, TReturnValue>;
593 /**
594 * Similar to callsArg.
595 * Causes the stub to call the first callback it receives with the provided arguments (if any).
596 * If a method accepts more than one callback, you need to use callsArg to have the stub invoke other callbacks than the first one.
597 */
598 yields(...args: any[]): SinonStub<TArgs, TReturnValue>;
599 /**
600 * Like above but with an additional parameter to pass the this context.
601 */
602 yieldsOn(context: any, ...args: any[]): SinonStub<TArgs, TReturnValue>;
603 yieldsRight(...args: any[]): SinonStub<TArgs, TReturnValue>;
604 /**
605 * Causes the spy to invoke a callback passed as a property of an object to the spy.
606 * Like yields, yieldsTo grabs the first matching argument, finds the callback and calls it with the (optional) arguments.
607 * @param property
608 * @param args
609 */
610 yieldsTo(property: string, ...args: any[]): SinonStub<TArgs, TReturnValue>;
611 /**
612 * Like above but with an additional parameter to pass the this context.
613 */
614 yieldsToOn(property: string, context: any, ...args: any[]): SinonStub<TArgs, TReturnValue>;
615 /**
616 * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed.
617 * In Node environment the callback is deferred with process.nextTick.
618 * In a browser the callback is deferred with setTimeout(callback, 0).
619 * @param args
620 */
621 yieldsAsync(...args: any[]): SinonStub<TArgs, TReturnValue>;
622 /**
623 * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed.
624 * In Node environment the callback is deferred with process.nextTick.
625 * In a browser the callback is deferred with setTimeout(callback, 0).
626 * @param context
627 * @param args
628 */
629 yieldsOnAsync(context: any, ...args: any[]): SinonStub<TArgs, TReturnValue>;
630 /**
631 * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed.
632 * In Node environment the callback is deferred with process.nextTick.
633 * In a browser the callback is deferred with setTimeout(callback, 0).
634 * @param property
635 * @param args
636 */
637 yieldsToAsync(property: string, ...args: any[]): SinonStub<TArgs, TReturnValue>;
638 /**
639 * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed.
640 * In Node environment the callback is deferred with process.nextTick.
641 * In a browser the callback is deferred with setTimeout(callback, 0).
642 * @param property
643 * @param context
644 * @param args
645 */
646 yieldsToOnAsync(property: string, context: any, ...args: any[]): SinonStub<TArgs, TReturnValue>;
647 /**
648 * Stubs the method only for the provided arguments.
649 * This is useful to be more expressive in your assertions, where you can access the spy with the same call.
650 * It is also useful to create a stub that can act differently in response to different arguments.
651 * @param args
652 */
653 withArgs(...args: MatchPartialArguments<TArgs>): SinonStub<TArgs, TReturnValue>;
654 }
655
656 interface SinonStubStatic {
657 /* tslint:disable:no-unnecessary-generics */
658
659 /**
660 * Creates an anonymous stub function
661 */
662 <TArgs extends readonly any[] = any[], R = any>(): SinonStub<TArgs, R>;
663
664 /* tslint:enable:no-unnecessary-generics */
665
666 /**
667 * Stubs all the object’s methods.
668 * Note that it’s usually better practice to stub individual methods, particularly on objects that you don’t understand or control all the methods for (e.g. library dependencies).
669 * Stubbing individual methods tests intent more precisely and is less susceptible to unexpected behavior as the object’s code evolves.
670 * If you want to create a stub object of MyConstructor, but don’t want the constructor to be invoked, use this utility function.
671 */
672 <T>(obj: T): SinonStubbedInstance<T>;
673 /**
674 * Replaces obj.method with a stub function.
675 * An exception is thrown if the property is not already a function.
676 * The original function can be restored by calling object.method.restore(); (or stub.restore();).
677 */
678 <T, K extends keyof T>(
679 obj: T,
680 method: K,
681 ): T[K] extends (...args: infer TArgs) => infer TReturnValue ? SinonStub<TArgs, TReturnValue>
682 : SinonStub;
683 }
684
685 interface SinonExpectation extends SinonStub {
686 /**
687 * Specify the minimum amount of calls expected.
688 */
689 atLeast(n: number): SinonExpectation;
690 /**
691 * Specify the maximum amount of calls expected.
692 * @param n
693 */
694 atMost(n: number): SinonExpectation;
695 /**
696 * Expect the method to never be called.
697 */
698 never(): SinonExpectation;
699 /**
700 * Expect the method to be called exactly once.
701 */
702 once(): SinonExpectation;
703 /**
704 * Expect the method to be called exactly twice.
705 */
706 twice(): SinonExpectation;
707 /**
708 * Expect the method to be called exactly thrice.
709 */
710 thrice(): SinonExpectation;
711 /**
712 * Expect the method to be called exactly @param n times.
713 */
714 exactly(n: number): SinonExpectation;
715 /**
716 * Expect the method to be called with the provided arguments and possibly others.
717 * An expectation instance only holds onto a single set of arguments specified with withArgs.
718 * Subsequent calls will overwrite the previously-specified set of arguments (even if they are different),
719 * so it is generally not intended that this method be invoked more than once per test case.
720 * @param args
721 */
722 withArgs(...args: any[]): SinonExpectation;
723 /**
724 * Expect the method to be called with the provided arguments and no others.
725 * An expectation instance only holds onto a single set of arguments specified with withExactArgs.
726 * Subsequent calls will overwrite the previously-specified set of arguments (even if they are different),
727 * so it is generally not intended that this method be invoked more than once per test case.
728 * @param args
729 */
730 withExactArgs(...args: any[]): SinonExpectation;
731 on(obj: any): SinonExpectation;
732 /**
733 * Verifies all expectations on the mock.
734 * If any expectation is not satisfied, an exception is thrown.
735 * Also restores the mocked methods.
736 */
737 verify(): SinonExpectation;
738 /**
739 * Restores all mocked methods.
740 */
741 restore(): void;
742 }
743
744 interface SinonExpectationStatic {
745 /**
746 * Creates an expectation without a mock object, basically an anonymous mock function.
747 * Method name is optional and is used in exception messages to make them more readable.
748 * @param methodName
749 */
750 create(methodName?: string): SinonExpectation;
751 }
752
753 interface SinonMock {
754 /**
755 * Overrides obj.method with a mock function and returns it.
756 */
757 expects(method: string): SinonExpectation;
758 /**
759 * Restores all mocked methods.
760 */
761 restore(): void;
762 /**
763 * Verifies all expectations on the mock.
764 * If any expectation is not satisfied, an exception is thrown.
765 * Also restores the mocked methods.
766 */
767 verify(): void;
768 }
769
770 interface SinonMockStatic {
771 (name?: string): SinonExpectation;
772 /**
773 * Creates a mock for the provided object.
774 * Does not change the object, but returns a mock object to set expectations on the object’s methods.
775 */
776 (obj: any): SinonMock;
777 }
778
779 type SinonFakeTimers = FakeTimers.Clock & {
780 /**
781 * Restores the original clock
782 * Identical to uninstall()
783 */
784 restore(): void;
785 };
786
787 interface SinonFakeUploadProgress {
788 eventListeners: {
789 progress: any[];
790 load: any[];
791 abort: any[];
792 error: any[];
793 };
794
795 addEventListener(event: string, listener: (e: Event) => any): void;
796 removeEventListener(event: string, listener: (e: Event) => any): void;
797 dispatchEvent(event: Event): void;
798 }
799
800 interface SinonFakeXMLHttpRequest {
801 // Properties
802 /**
803 * The URL set on the request object.
804 */
805 url: string;
806 /**
807 * The request method as a string.
808 */
809 method: string;
810 /**
811 * An object of all request headers, i.e.:
812 */
813 requestHeaders: any;
814 /**
815 * The request body
816 */
817 requestBody: string;
818 /**
819 * The request’s status code.
820 * undefined if the request has not been handled (see respond below)
821 */
822 status: number;
823 /**
824 * Only populated if the respond method is called (see below).
825 */
826 statusText: string;
827 /**
828 * Whether or not the request is asynchronous.
829 */
830 async: boolean;
831 /**
832 * Username, if any.
833 */
834 username: string;
835 /**
836 * Password, if any.
837 */
838 password: string;
839 withCredentials: boolean;
840 upload: SinonFakeUploadProgress;
841 /**
842 * When using respond, this property is populated with a parsed document if response headers indicate as much (see the spec)
843 */
844 responseXML: Document;
845 /**
846 * The value of the given response header, if the request has been responded to (see respond).
847 * @param header
848 */
849 getResponseHeader(header: string): string;
850 /**
851 * All response headers as an object.
852 */
853 getAllResponseHeaders(): any;
854
855 // Methods
856 /**
857 * Sets response headers (e.g. { "Content-Type": "text/html", ... }, updates the readyState property and fires onreadystatechange.
858 * @param headers
859 */
860 setResponseHeaders(headers: any): void;
861 /**
862 * Sets the respond body, updates the readyState property and fires onreadystatechange.
863 * Additionally, populates responseXML with a parsed document if response headers indicate as much.
864 */
865 setResponseBody(body: string): void;
866 /**
867 * Calls the above three methods.
868 */
869 respond(status: number, headers: any, body: string): void;
870 autoRespond(ms: number): void;
871 /**
872 * Simulates a network error on the request. The onerror handler will be called and the status will be 0.
873 */
874 error(): void;
875 onerror(): void;
876 }
877
878 interface SinonFakeXMLHttpRequestStatic {
879 new(): SinonFakeXMLHttpRequest;
880 /**
881 * Default false.
882 * When set to true, Sinon will check added filters if certain requests should be “unfaked”
883 */
884 useFilters: boolean;
885 /**
886 * Add a filter that will decide whether or not to fake a request.
887 * The filter will be called when xhr.open is called, with the exact same arguments (method, url, async, username, password).
888 * If the filter returns true, the request will not be faked.
889 * @param filter
890 */
891 addFilter(
892 filter: (method: string, url: string, async: boolean, username: string, password: string) => boolean,
893 ): void;
894 /**
895 * By assigning a function to the onCreate property of the returned object from useFakeXMLHttpRequest()
896 * you can subscribe to newly created FakeXMLHttpRequest objects. See below for the fake xhr object API.
897 * Using this observer means you can still reach objects created by e.g. jQuery.ajax (or other abstractions/frameworks).
898 * @param xhr
899 */
900 onCreate(xhr: SinonFakeXMLHttpRequest): void;
901 /**
902 * Restore original function(s).
903 */
904 restore(): void;
905 }
906
907 interface SinonFakeServer extends SinonFakeServerOptions {
908 // Properties
909 /**
910 * Used internally to determine the HTTP method used with the provided request.
911 * By default this method simply returns request.method.
912 * When server.fakeHTTPMethods is true, the method will return the value of the _method parameter if the method is “POST”.
913 * This method can be overridden to provide custom behavior.
914 * @param request
915 */
916 getHTTPMethod(request: SinonFakeXMLHttpRequest): string;
917 /**
918 * You can inspect the server.requests to verify request ordering, find unmatched requests or check that no requests has been done.
919 * server.requests is an array of all the FakeXMLHttpRequest objects that have been created.
920 */
921 requests: SinonFakeXMLHttpRequest[];
922
923 // Methods
924 /**
925 * Causes the server to respond to any request not matched by another response with the provided data. The default catch-all response is [404, {}, ""].
926 * A String representing the response body
927 * An Array with status, headers and response body, e.g. [200, { "Content-Type": "text/html", "Content-Length": 2 }, "OK"]
928 * A Function.
929 * Default status is 200 and default headers are none.
930 * When the response is a Function, it will be passed the request object. You must manually call respond on it to complete the request.
931 * @param body A String representing the response body
932 */
933 respondWith(body: string): void;
934 /**
935 * Causes the server to respond to any request not matched by another response with the provided data. The default catch-all response is [404, {}, ""].
936 * Default status is 200 and default headers are none.
937 * When the response is a Function, it will be passed the request object. You must manually call respond on it to complete the request.
938 * @param response An Array with status, headers and response body, e.g. [200, { "Content-Type": "text/html", "Content-Length": 2 }, "OK"]
939 */
940 respondWith(response: any[]): void;
941 /**
942 * Causes the server to respond to any request not matched by another response with the provided data. The default catch-all response is [404, {}, ""].
943 * Default status is 200 and default headers are none.
944 * When the response is a Function, it will be passed the request object. You must manually call respond on it to complete the request.
945 * @param fn A Function.
946 */
947 respondWith(fn: (xhr: SinonFakeXMLHttpRequest) => void): void;
948 /**
949 * Responds to all requests to given URL, e.g. /posts/1.
950 */
951 respondWith(url: string, body: string): void;
952 /**
953 * Responds to all requests to given URL, e.g. /posts/1.
954 */
955 respondWith(url: string, response: any[]): void;
956 /**
957 * Responds to all requests to given URL, e.g. /posts/1.
958 */
959 respondWith(url: string, fn: (xhr: SinonFakeXMLHttpRequest) => void): void;
960 /**
961 * Responds to all method requests to the given URL with the given response.
962 * method is an HTTP verb.
963 */
964 respondWith(method: string, url: string, body: string): void;
965 /**
966 * Responds to all method requests to the given URL with the given response.
967 * method is an HTTP verb.
968 */
969 respondWith(method: string, url: string, response: any[]): void;
970 /**
971 * Responds to all method requests to the given URL with the given response.
972 * method is an HTTP verb.
973 */
974 respondWith(method: string, url: string, fn: (xhr: SinonFakeXMLHttpRequest) => void): void;
975 /**
976 * URL may be a regular expression, e.g. /\\/post\\//\\d+
977 * If the response is a Function, it will be passed any capture groups from the regular expression along with the XMLHttpRequest object:
978 */
979 respondWith(url: RegExp, body: string): void;
980 /**
981 * URL may be a regular expression, e.g. /\\/post\\//\\d+
982 * If the response is a Function, it will be passed any capture groups from the regular expression along with the XMLHttpRequest object:
983 */
984 respondWith(url: RegExp, response: any[]): void;
985 /**
986 * URL may be a regular expression, e.g. /\\/post\\//\\d+
987 * If the response is a Function, it will be passed any capture groups from the regular expression along with the XMLHttpRequest object:
988 */
989 respondWith(url: RegExp, fn: (xhr: SinonFakeXMLHttpRequest) => void): void;
990 /**
991 * Responds to all method requests to URLs matching the regular expression.
992 */
993 respondWith(method: string, url: RegExp, body: string): void;
994 /**
995 * Responds to all method requests to URLs matching the regular expression.
996 */
997 respondWith(method: string, url: RegExp, response: any[]): void;
998 /**
999 * Responds to all method requests to URLs matching the regular expression.
1000 */
1001 respondWith(method: string, url: RegExp, fn: (xhr: SinonFakeXMLHttpRequest) => void): void;
1002 /**
1003 * Causes all queued asynchronous requests to receive a response.
1004 * If none of the responses added through respondWith match, the default response is [404, {}, ""].
1005 * Synchronous requests are responded to immediately, so make sure to call respondWith upfront.
1006 * If called with arguments, respondWith will be called with those arguments before responding to requests.
1007 */
1008 respond(): void;
1009 restore(): void;
1010 }
1011
1012 interface SinonFakeServerOptions {
1013 /**
1014 * When set to true, causes the server to automatically respond to incoming requests after a timeout.
1015 * The default timeout is 10ms but you can control it through the autoRespondAfter property.
1016 * Note that this feature is intended to help during mockup development, and is not suitable for use in tests.
1017 */
1018 autoRespond: boolean;
1019 /**
1020 * When autoRespond is true, respond to requests after this number of milliseconds. Default is 10.
1021 */
1022 autoRespondAfter: number;
1023 /**
1024 * If set to true, server will find _method parameter in POST body and recognize that as the actual method.
1025 * Supports a pattern common to Ruby on Rails applications. For custom HTTP method faking, override server.getHTTPMethod(request).
1026 */
1027 fakeHTTPMethods: boolean;
1028 /**
1029 * If set, the server will respond to every request immediately and synchronously.
1030 * This is ideal for faking the server from within a test without having to call server.respond() after each request made in that test.
1031 * As this is synchronous and immediate, this is not suitable for simulating actual network latency in tests or mockups.
1032 * To simulate network latency with automatic responses, see server.autoRespond and server.autoRespondAfter.
1033 */
1034 respondImmediately: boolean;
1035 }
1036
1037 interface SinonFakeServerStatic {
1038 create(options?: Partial<SinonFakeServerOptions>): SinonFakeServer;
1039 }
1040
1041 interface SinonExposeOptions {
1042 prefix: string;
1043 includeFail: boolean;
1044 }
1045
1046 interface SinonAssert {
1047 // Properties
1048 /**
1049 * Defaults to AssertError.
1050 */
1051 failException: string;
1052 /**
1053 * Every assertion fails by calling this method.
1054 * By default it throws an error of type sinon.assert.failException.
1055 * If the test framework looks for assertion errors by checking for a specific exception, you can simply override the kind of exception thrown.
1056 * If that does not fit with your testing framework of choice, override the fail method to do the right thing.
1057 */
1058 fail(message?: string): void; // Overridable
1059 /**
1060 * Called every time assertion passes.
1061 * Default implementation does nothing.
1062 */
1063 pass(assertion: any): void; // Overridable
1064
1065 // Methods
1066
1067 /**
1068 * Passes if spy was never called
1069 * @param spy
1070 */
1071 notCalled(spy: SinonSpy<any>): void;
1072 /**
1073 * Passes if spy was called at least once.
1074 */
1075 called(spy: SinonSpy<any>): void;
1076 /**
1077 * Passes if spy was called once and only once.
1078 */
1079 calledOnce(spy: SinonSpy<any>): void;
1080 /**
1081 * Passes if spy was called exactly twice.
1082 */
1083 calledTwice(spy: SinonSpy<any>): void;
1084 /**
1085 * Passes if spy was called exactly three times.
1086 */
1087 calledThrice(spy: SinonSpy<any>): void;
1088 /**
1089 * Passes if spy was called exactly num times.
1090 */
1091 callCount(spy: SinonSpy<any>, count: number): void;
1092 /**
1093 * Passes if provided spies were called in the specified order.
1094 * @param spies
1095 */
1096 callOrder(...spies: Array<SinonSpy<any>>): void;
1097 /**
1098 * Passes if spy was ever called with obj as its this value.
1099 * It’s possible to assert on a dedicated spy call: sinon.assert.calledOn(spy.firstCall, arg1, arg2, ...);.
1100 */
1101 calledOn(spyOrSpyCall: SinonSpy<any> | SinonSpyCall<any>, obj: any): void;
1102 /**
1103 * Passes if spy was always called with obj as its this value.
1104 */
1105 alwaysCalledOn(spy: SinonSpy<any>, obj: any): void;
1106
1107 /**
1108 * Passes if spy was called with the provided arguments.
1109 * It’s possible to assert on a dedicated spy call: sinon.assert.calledWith(spy.firstCall, arg1, arg2, ...);.
1110 * @param spyOrSpyCall
1111 * @param args
1112 */
1113 calledWith<TArgs extends any[]>(
1114 spyOrSpyCall: SinonSpy<TArgs> | SinonSpyCall<TArgs>,
1115 ...args: MatchPartialArguments<TArgs>
1116 ): void;
1117 /**
1118 * Passes if spy was always called with the provided arguments.
1119 * @param spy
1120 * @param args
1121 */
1122 alwaysCalledWith<TArgs extends any[]>(spy: SinonSpy<TArgs>, ...args: MatchPartialArguments<TArgs>): void;
1123 /**
1124 * Passes if spy was never called with the provided arguments.
1125 * @param spy
1126 * @param args
1127 */
1128 neverCalledWith<TArgs extends any[]>(spy: SinonSpy<TArgs>, ...args: MatchPartialArguments<TArgs>): void;
1129 /**
1130 * Passes if spy was called with the provided arguments and no others.
1131 * It’s possible to assert on a dedicated spy call: sinon.assert.calledWithExactly(spy.getCall(1), arg1, arg2, ...);.
1132 * @param spyOrSpyCall
1133 * @param args
1134 */
1135 calledWithExactly<TArgs extends any[]>(
1136 spyOrSpyCall: SinonSpy<TArgs> | SinonSpyCall<TArgs>,
1137 ...args: MatchExactArguments<TArgs>
1138 ): void;
1139 /**
1140 * Passes if spy was called at exactly once with the provided arguments and no others.
1141 * @param spyOrSpyCall
1142 * @param args
1143 */
1144 calledOnceWithExactly<TArgs extends any[]>(
1145 spyOrSpyCall: SinonSpy<TArgs> | SinonSpyCall<TArgs>,
1146 ...args: MatchExactArguments<TArgs>
1147 ): void;
1148 /**
1149 * Passes if spy was always called with the provided arguments and no others.
1150 */
1151 alwaysCalledWithExactly<TArgs extends any[]>(spy: SinonSpy<TArgs>, ...args: MatchExactArguments<TArgs>): void;
1152 /**
1153 * Passes if spy was called with matching arguments.
1154 * This behaves the same way as sinon.assert.calledWith(spy, sinon.match(arg1), sinon.match(arg2), ...).
1155 * It's possible to assert on a dedicated spy call: sinon.assert.calledWithMatch(spy.secondCall, arg1, arg2, ...);.
1156 */
1157 calledWithMatch<TArgs extends any[]>(
1158 spyOrSpyCall: SinonSpy<TArgs> | SinonSpyCall<TArgs>,
1159 ...args: MatchPartialArguments<TArgs>
1160 ): void;
1161 /**
1162 * Passes if spy was called once with matching arguments.
1163 * This behaves the same way as calling both sinon.assert.calledOnce(spy) and
1164 * sinon.assert.calledWithMatch(spy, ...).
1165 */
1166 calledOnceWithMatch<TArgs extends any[]>(
1167 spyOrSpyCall: SinonSpy<TArgs> | SinonSpyCall<TArgs>,
1168 ...args: MatchPartialArguments<TArgs>
1169 ): void;
1170 /**
1171 * Passes if spy was always called with matching arguments.
1172 * This behaves the same way as sinon.assert.alwaysCalledWith(spy, sinon.match(arg1), sinon.match(arg2), ...).
1173 */
1174 alwaysCalledWithMatch<TArgs extends any[]>(spy: SinonSpy<TArgs>, ...args: MatchPartialArguments<TArgs>): void;
1175 /**
1176 * Passes if spy was never called with matching arguments.
1177 * This behaves the same way as sinon.assert.neverCalledWith(spy, sinon.match(arg1), sinon.match(arg2), ...).
1178 * @param spy
1179 * @param args
1180 */
1181 neverCalledWithMatch<TArgs extends any[]>(spy: SinonSpy<TArgs>, ...args: MatchPartialArguments<TArgs>): void;
1182 /**
1183 * Passes if spy was called with the new operator.
1184 * It’s possible to assert on a dedicated spy call: sinon.assert.calledWithNew(spy.secondCall, arg1, arg2, ...);.
1185 * @param spyOrSpyCall
1186 */
1187 calledWithNew(spyOrSpyCall: SinonSpy<any> | SinonSpyCall<any>): void;
1188 /**
1189 * Passes if spy threw any exception.
1190 */
1191 threw(spyOrSpyCall: SinonSpy<any> | SinonSpyCall<any>): void;
1192 /**
1193 * Passes if spy threw the given exception.
1194 * The exception is an actual object.
1195 * It’s possible to assert on a dedicated spy call: sinon.assert.threw(spy.thirdCall, exception);.
1196 */
1197 threw(spyOrSpyCall: SinonSpy<any> | SinonSpyCall<any>, exception: string): void;
1198 /**
1199 * Passes if spy threw the given exception.
1200 * The exception is a String denoting its type.
1201 * It’s possible to assert on a dedicated spy call: sinon.assert.threw(spy.thirdCall, exception);.
1202 */
1203 threw(spyOrSpyCall: SinonSpy<any> | SinonSpyCall<any>, exception: any): void;
1204
1205 /**
1206 * Like threw, only required for all calls to the spy.
1207 */
1208 alwaysThrew(spy: SinonSpy<any>): void;
1209 /**
1210 * Like threw, only required for all calls to the spy.
1211 */
1212 alwaysThrew(spy: SinonSpy<any>, exception: string): void;
1213 /**
1214 * Like threw, only required for all calls to the spy.
1215 */
1216 alwaysThrew(spy: SinonSpy<any>, exception: any): void;
1217
1218 /**
1219 * Uses sinon.match to test if the arguments can be considered a match.
1220 */
1221 match(actual: any, expected: any): void;
1222 /**
1223 * Exposes assertions into another object, to better integrate with the test framework.
1224 * For instance, JsTestDriver uses global assertions, and to make Sinon.JS assertions appear alongside them, you can do.
1225 * @example sinon.assert.expose(this);
1226 * This will give you assertCalled(spy),assertCallOrder(spy1, spy2, ...) and so on.
1227 * The method accepts an optional options object with two options.
1228 */
1229 expose(obj: any, options?: Partial<SinonExposeOptions>): void;
1230 }
1231
1232 interface SinonMatcher {
1233 /**
1234 * All matchers implement and and or. This allows to logically combine mutliple matchers.
1235 * The result is a new matchers that requires both (and) or one of the matchers (or) to return true.
1236 * @example var stringOrNumber = sinon.match.string.or(sinon.match.number);
1237 * var bookWithPages = sinon.match.instanceOf(Book).and(sinon.match.has("pages"));
1238 */
1239 and(expr: SinonMatcher): SinonMatcher;
1240 /**
1241 * All matchers implement and and or. This allows to logically combine mutliple matchers.
1242 * The result is a new matchers that requires both (and) or one of the matchers (or) to return true.
1243 * @example var stringOrNumber = sinon.match.string.or(sinon.match.number);
1244 * var bookWithPages = sinon.match.instanceOf(Book).and(sinon.match.has("pages"));
1245 */
1246 or(expr: SinonMatcher): SinonMatcher;
1247 test(val: any): boolean;
1248 }
1249
1250 interface SinonArrayMatcher extends SinonMatcher {
1251 /**
1252 * Requires an Array to be deep equal another one.
1253 */
1254 deepEquals(expected: any[]): SinonMatcher;
1255 /**
1256 * Requires an Array to start with the same values as another one.
1257 */
1258 startsWith(expected: any[]): SinonMatcher;
1259 /**
1260 * Requires an Array to end with the same values as another one.
1261 */
1262 endsWith(expected: any[]): SinonMatcher;
1263 /**
1264 * Requires an Array to contain each one of the values the given array has.
1265 */
1266 contains(expected: any[]): SinonMatcher;
1267 }
1268
1269 interface SimplifiedSet {
1270 has(el: any): boolean;
1271 }
1272
1273 interface SimplifiedMap extends SimplifiedSet {
1274 get(key: any): any;
1275 }
1276
1277 interface SinonMapMatcher extends SinonMatcher {
1278 /**
1279 * Requires a Map to be deep equal another one.
1280 */
1281 deepEquals(expected: SimplifiedMap): SinonMatcher;
1282 /**
1283 * Requires a Map to contain each one of the items the given map has.
1284 */
1285 contains(expected: SimplifiedMap): SinonMatcher;
1286 }
1287
1288 interface SinonSetMatcher extends SinonMatcher {
1289 /**
1290 * Requires a Set to be deep equal another one.
1291 */
1292 deepEquals(expected: SimplifiedSet): SinonMatcher;
1293 /**
1294 * Requires a Set to contain each one of the items the given set has.
1295 */
1296 contains(expected: SimplifiedSet): SinonMatcher;
1297 }
1298
1299 interface SinonMatch {
1300 /**
1301 * Requires the value to be == to the given number.
1302 */
1303 (value: number): SinonMatcher;
1304 /**
1305 * Requires the value to be a string and have the expectation as a substring.
1306 */
1307 (value: string): SinonMatcher;
1308 /**
1309 * Requires the value to be a string and match the given regular expression.
1310 */
1311 (expr: RegExp): SinonMatcher;
1312 /**
1313 * See custom matchers.
1314 */
1315 (callback: (value: any) => boolean, message?: string): SinonMatcher;
1316 /**
1317 * Requires the value to be not null or undefined and have at least the same properties as expectation.
1318 * This supports nested matchers.
1319 */
1320 (obj: object): SinonMatcher;
1321 /**
1322 * Matches anything.
1323 */
1324 any: SinonMatcher;
1325 /**
1326 * Requires the value to be defined.
1327 */
1328 defined: SinonMatcher;
1329 /**
1330 * Requires the value to be truthy.
1331 */
1332 truthy: SinonMatcher;
1333 /**
1334 * Requires the value to be falsy.
1335 */
1336 falsy: SinonMatcher;
1337 /**
1338 * Requires the value to be a Boolean
1339 */
1340 bool: SinonMatcher;
1341 /**
1342 * Requires the value to be a Number.
1343 */
1344 number: SinonMatcher;
1345 /**
1346 * Requires the value to be a String.
1347 */
1348 string: SinonMatcher;
1349 /**
1350 * Requires the value to be an Object.
1351 */
1352 object: SinonMatcher;
1353 /**
1354 * Requires the value to be a Function.
1355 */
1356 func: SinonMatcher;
1357 /**
1358 * Requires the value to be a Map.
1359 */
1360 map: SinonMapMatcher;
1361 /**
1362 * Requires the value to be a Set.
1363 */
1364 set: SinonSetMatcher;
1365 /**
1366 * Requires the value to be an Array.
1367 */
1368 array: SinonArrayMatcher;
1369 /**
1370 * Requires the value to be a regular expression.
1371 */
1372 regexp: SinonMatcher;
1373 /**
1374 * Requires the value to be a Date object.
1375 */
1376 date: SinonMatcher;
1377 /**
1378 * Requires the value to be a Symbol.
1379 */
1380 symbol: SinonMatcher;
1381 /**
1382 * Requires the value to be in the specified array.
1383 */
1384 in(allowed: any[]): SinonMatcher;
1385 /**
1386 * Requires the value to strictly equal ref.
1387 */
1388 same(obj: any): SinonMatcher;
1389 /**
1390 * Requires the value to be of the given type, where type can be one of "undefined", "null", "boolean", "number", "string", "object", "function", "array", "regexp", "date" or "symbol".
1391 */
1392 typeOf(type: string): SinonMatcher;
1393 /**
1394 * Requires the value to be an instance of the given type.
1395 */
1396 instanceOf(type: any): SinonMatcher;
1397 /**
1398 * Requires the value to define the given property.
1399 * The property might be inherited via the prototype chain.
1400 * If the optional expectation is given, the value of the property is deeply compared with the expectation.
1401 * The expectation can be another matcher.
1402 * @param property
1403 * @param expect
1404 */
1405 has(property: string, expect?: any): SinonMatcher;
1406 /**
1407 * Same as sinon.match.has but the property must be defined by the value itself. Inherited properties are ignored.
1408 * @param property
1409 * @param expect
1410 */
1411 hasOwn(property: string, expect?: any): SinonMatcher;
1412 /**
1413 * Requires the value to define the given propertyPath. Dot (prop.prop) and bracket (prop[0]) notations are supported as in Lodash.get.
1414 * The propertyPath might be inherited via the prototype chain.
1415 * If the optional expectation is given, the value at the propertyPath is deeply compared with the expectation.
1416 * The expectation can be another matcher.
1417 */
1418 hasNested(path: string, expect?: any): SinonMatcher;
1419 /**
1420 * Requires every element of an Array, Set or Map, or alternatively every value of an Object to match the given matcher.
1421 */
1422 every(matcher: SinonMatcher): SinonMatcher;
1423 /**
1424 * Requires any element of an Array, Set or Map, or alternatively any value of an Object to match the given matcher.
1425 */
1426 some(matcher: SinonMatcher): SinonMatcher;
1427 }
1428
1429 interface SinonSandboxConfig {
1430 /**
1431 * The sandbox’s methods can be injected into another object for convenience.
1432 * The injectInto configuration option can name an object to add properties to.
1433 */
1434 injectInto: object | null;
1435 /**
1436 * What properties to inject.
1437 * Note that simply naming “server” here is not sufficient to have a server property show up in the target object,
1438 * you also have to set useFakeServer to true.
1439 */
1440 properties: string[];
1441 /**
1442 * If set to true, the sandbox will have a clock property.
1443 * You can optionally pass in a configuration object that follows the specification for fake timers, such as { toFake: ["setTimeout", "setInterval"] }.
1444 */
1445 useFakeTimers: boolean | Partial<FakeTimers.FakeTimerInstallOpts>;
1446 /**
1447 * If true, server and requests properties are added to the sandbox. Can also be an object to use for fake server.
1448 * The default one is sinon.fakeServer, but if you’re using jQuery 1.3.x or some other library that does not set the XHR’s onreadystatechange handler,
1449 * you might want to do:
1450 */
1451 useFakeServer: boolean | SinonFakeServer;
1452 /**
1453 * The assert options can help limit the amount of output produced by assert.fail
1454 */
1455 assertOptions: {
1456 shouldLimitAssertionLogs?: boolean;
1457 assertionLogLimit?: number;
1458 };
1459 }
1460
1461 /**
1462 * Stubbed type of an object with members replaced by stubs.
1463 *
1464 * @template TType Type being stubbed.
1465 */
1466 type StubbableType<TType> = Function & { prototype: TType };
1467
1468 /**
1469 * An instance of a stubbed object type with functions replaced by stubs.
1470 *
1471 * @template TType Object type being stubbed.
1472 */
1473 type SinonStubbedInstance<TType> =
1474 & TType
1475 & {
1476 [P in keyof TType]: SinonStubbedMember<TType[P]>;
1477 };
1478
1479 /**
1480 * Replaces a type with a Sinon stub if it's a function.
1481 */
1482 type SinonStubbedMember<T> = T extends (...args: infer TArgs) => infer TReturnValue ? SinonStub<TArgs, TReturnValue>
1483 : T;
1484
1485 interface SinonFake {
1486 /**
1487 * Creates a basic fake, with no behavior
1488 */
1489 <TArgs extends readonly any[] = any[], TReturnValue = any>(): SinonSpy<TArgs, TReturnValue>;
1490 /**
1491 * Wraps an existing Function to record all interactions, while leaving it up to the func to provide the behavior.
1492 * This is useful when complex behavior not covered by the sinon.fake.* methods is required or when wrapping an existing function or method.
1493 */
1494 <TArgs extends readonly any[] = any[], TReturnValue = any>(fn: (...args: TArgs) => TReturnValue): SinonSpy<
1495 TArgs,
1496 TReturnValue
1497 >;
1498 /**
1499 * Creates a fake that returns the val argument
1500 * @param val Returned value
1501 */
1502 returns<TArgs extends readonly any[] = any[], TReturnValue = any>(
1503 val: TReturnValue,
1504 ): SinonSpy<TArgs, TReturnValue>;
1505 /**
1506 * Creates a fake that throws an Error with the provided value as the message property.
1507 * If an Error is passed as the val argument, then that will be the thrown value. If any other value is passed, then that will be used for the message property of the thrown Error.
1508 * @param val Returned value or throw value if an Error
1509 */
1510 throws<TArgs extends readonly any[] = any[], TReturnValue = any>(
1511 val: Error | string,
1512 ): SinonSpy<TArgs, TReturnValue>;
1513 /**
1514 * Creates a fake that returns a resolved Promise for the passed value.
1515 * @param val Resolved promise
1516 */
1517 resolves<TArgs extends readonly any[] = any[], TReturnValue = any>(
1518 val: TReturnValue extends PromiseLike<infer TResolveValue> ? TResolveValue : any,
1519 ): SinonSpy<TArgs, TReturnValue>;
1520 /**
1521 * Creates a fake that returns a rejected Promise for the passed value.
1522 * If an Error is passed as the value argument, then that will be the value of the promise.
1523 * If any other value is passed, then that will be used for the message property of the Error returned by the promise.
1524 * @param val Rejected promise
1525 */
1526 rejects<TArgs extends readonly any[] = any[], TReturnValue = any>(val: any): SinonSpy<TArgs, TReturnValue>;
1527 /**
1528 * fake expects the last argument to be a callback and will invoke it with the given arguments.
1529 */
1530 yields<TArgs extends readonly any[] = any[], TReturnValue = any>(...args: any[]): SinonSpy<TArgs, TReturnValue>;
1531 /**
1532 * fake expects the last argument to be a callback and will invoke it asynchronously with the given arguments.
1533 */
1534 yieldsAsync<TArgs extends readonly any[] = any[], TReturnValue = any>(
1535 ...args: any[]
1536 ): SinonSpy<TArgs, TReturnValue>;
1537 }
1538
1539 interface SandboxReplace {
1540 /**
1541 * Replaces property on object with replacement argument.
1542 * Attempts to replace an already replaced value cause an exception.
1543 * replacement can be any value, including spies, stubs and fakes.
1544 * This method only works on non-accessor properties, for replacing accessors,
1545 * use sandbox.replaceGetter() and sandbox.replaceSetter().
1546 */
1547 <T, TKey extends keyof T, R extends T[TKey] = T[TKey]>(obj: T, prop: TKey, replacement: R): R;
1548
1549 /**
1550 * Assigns a value to a property on object with replacement argument.
1551 * replacement can be any value, including spies, stubs and fakes.
1552 * This method only works on accessor properties.
1553 */
1554 usingAccessor<T, TKey extends keyof T, R extends T[TKey] = T[TKey]>(obj: T, prop: TKey, replacement: R): R;
1555 }
1556
1557 interface SinonSandbox {
1558 /**
1559 * A convenience reference for sinon.assert
1560 * Since sinon@2.0.0
1561 */
1562 assert: SinonAssert;
1563 clock: SinonFakeTimers;
1564 requests: SinonFakeXMLHttpRequest[];
1565 server: SinonFakeServer;
1566 match: SinonMatch;
1567 /**
1568 * Works exactly like sinon.spy
1569 */
1570 spy: SinonSpyStatic;
1571 /**
1572 * Works exactly like sinon.stub.
1573 */
1574 stub: SinonStubStatic;
1575 /**
1576 * Works exactly like sinon.mock
1577 */
1578 mock: SinonMockStatic;
1579
1580 fake: SinonFake;
1581
1582 /**
1583 * * No param : Causes Sinon to replace the global setTimeout, clearTimeout, setInterval, clearInterval, setImmediate, clearImmediate, process.hrtime, performance.now(when available)
1584 * and Date with a custom implementation which is bound to the returned clock object.
1585 * Starts the clock at the UNIX epoch (timestamp of 0).
1586 * * Now : As above, but rather than starting the clock with a timestamp of 0, start at the provided timestamp now.
1587 * Since sinon@2.0.0
1588 * You can also pass in a Date object, and its getTime() will be used for the starting timestamp.
1589 * * Config : As above, but allows further configuration options, some of which are:
1590 * * config.now - Number/Date - installs lolex with the specified unix epoch (default: 0)
1591 * * config.toFake - String[ ] - an array with explicit function names to fake.
1592 * By default lolex will automatically fake all methods except process.nextTick. You could, however, still fake nextTick by providing it explicitly
1593 * * config.shouldAdvanceTime - Boolean - tells lolex to increment mocked time automatically based on the real system time shift (default: false)
1594 * * Please visit the lolex.install documentation for the full feature set.
1595 * * Important note: when faking nextTick, normal calls to process.nextTick() would not execute automatically as they would during normal event-loop phases.
1596 * You would have to call either clock.next(), clock.tick(), clock.runAll() or clock.runToLast() (see example below). Please refer to the lolex documentation for more information.
1597 * @param config
1598 */
1599 useFakeTimers(config?: number | Date | Partial<FakeTimers.FakeTimerInstallOpts>): SinonFakeTimers;
1600 /**
1601 * Causes Sinon to replace the native XMLHttpRequest object in browsers that support it with a custom implementation which does not send actual requests.
1602 * In browsers that support ActiveXObject, this constructor is replaced, and fake objects are returned for XMLHTTP progIds.
1603 * Other progIds, such as XMLDOM are left untouched.
1604 * The native XMLHttpRequest object will be available at sinon.xhr.XMLHttpRequest
1605 */
1606 useFakeXMLHttpRequest(): SinonFakeXMLHttpRequestStatic;
1607 /**
1608 * Fakes XHR and binds a server object to the sandbox such that it too is restored when calling sandbox.restore().
1609 * Access requests through sandbox.requests and server through sandbox.server
1610 */
1611 useFakeServer(): SinonFakeServer;
1612 /**
1613 * Restores all fakes created through sandbox.
1614 */
1615 restore(): void;
1616 /**
1617 * Resets the internal state of all fakes created through sandbox.
1618 */
1619 reset(): void;
1620 /**
1621 * Resets the history of all stubs created through the sandbox.
1622 * Since sinon@2.0.0
1623 */
1624 resetHistory(): void;
1625 /**
1626 * Resets the behaviour of all stubs created through the sandbox.
1627 * Since sinon@2.0.0
1628 */
1629 resetBehavior(): void;
1630 /**
1631 * Causes all stubs created from the sandbox to return promises using a specific Promise library instead of the global one when using stub.rejects or stub.resolves.
1632 * Returns the stub to allow chaining.
1633 * Since sinon@2.0.0
1634 */
1635 usingPromise(promiseLibrary: any): SinonSandbox;
1636 /**
1637 * Verifies all mocks created through the sandbox.
1638 */
1639 verify(): void;
1640 /**
1641 * Verifies all mocks and restores all fakes created through the sandbox.
1642 */
1643 verifyAndRestore(): void;
1644
1645 replace: SandboxReplace;
1646
1647 /**
1648 * Replaces getter for property on object with replacement argument. Attempts to replace an already replaced getter cause an exception.
1649 * replacement must be a Function, and can be instances of spies, stubs and fakes.
1650 * @param obj
1651 * @param prop
1652 * @param replacement
1653 */
1654 replaceGetter<T, TKey extends keyof T>(obj: T, prop: TKey, replacement: () => T[TKey]): () => T[TKey];
1655
1656 /**
1657 * Replaces setter for property on object with replacement argument. Attempts to replace an already replaced setter cause an exception.
1658 * replacement must be a Function, and can be instances of spies, stubs and fakes.
1659 * @param obj
1660 * @param prop
1661 * @param replacement
1662 */
1663 replaceSetter<T, TKey extends keyof T>(
1664 obj: T,
1665 prop: TKey,
1666 replacement: (val: T[TKey]) => void,
1667 ): (val: T[TKey]) => void;
1668
1669 /**
1670 * Creates a new object with the given functions as the prototype and stubs all implemented functions.
1671 *
1672 * @template TType Type being stubbed.
1673 * @param constructor Object or class to stub.
1674 * @param overrides An optional map overriding created stubs
1675 * @returns A stubbed version of the constructor.
1676 * @remarks The given constructor function is not invoked. See also the stub API.
1677 */
1678 createStubInstance<TType>(
1679 constructor: StubbableType<TType>,
1680 overrides?: {
1681 [K in keyof TType]?:
1682 | SinonStubbedMember<TType[K]>
1683 | (TType[K] extends (...args: any[]) => infer R ? R : TType[K]);
1684 },
1685 ): SinonStubbedInstance<TType>;
1686
1687 /**
1688 * Defines a property on the given object which will be torn down when
1689 * the sandbox is restored
1690 */
1691 define(
1692 obj: object,
1693 key: PropertyKey,
1694 value: unknown,
1695 ): void;
1696 }
1697
1698 type SinonPromise<T> = Promise<T> & {
1699 status: "pending" | "resolved" | "rejected";
1700 resolve(val: unknown): Promise<T>;
1701 reject(reason: unknown): Promise<void>;
1702 resolvedValue?: T;
1703 rejectedValue?: unknown;
1704 };
1705
1706 interface SinonApi {
1707 expectation: SinonExpectationStatic;
1708
1709 clock: {
1710 create(now: number | Date): FakeTimers.Clock;
1711 };
1712
1713 FakeXMLHttpRequest: SinonFakeXMLHttpRequestStatic;
1714
1715 fakeServer: SinonFakeServerStatic;
1716 fakeServerWithClock: SinonFakeServerStatic;
1717
1718 /**
1719 * Creates a new sandbox object with spies, stubs, and mocks.
1720 * @param config
1721 */
1722 createSandbox(config?: Partial<SinonSandboxConfig>): SinonSandbox;
1723 defaultConfig: Partial<SinonSandboxConfig>;
1724
1725 /**
1726 * Add a custom behavior.
1727 * The name will be available as a function on stubs, and the chaining mechanism
1728 * will be set up for you (e.g. no need to return anything from your function,
1729 * its return value will be ignored). The fn will be passed the fake instance
1730 * as its first argument, and then the user's arguments.
1731 */
1732 addBehavior: (name: string, fn: (fake: SinonStub, ...userArgs: any[]) => void) => void;
1733
1734 /**
1735 * Replace the default formatter used when formatting ECMAScript object
1736 * An example converts a basic object, such as {id: 42 }, to a string
1737 * on a format of your choosing, such as "{ id: 42 }"
1738 */
1739 setFormatter: (customFormatter: (...args: any[]) => string) => void;
1740
1741 promise<T = unknown>(
1742 executor?: (resolve: (value: T) => void, reject: (reason?: unknown) => void) => void,
1743 ): SinonPromise<T>;
1744 }
1745
1746 type SinonStatic = SinonSandbox & SinonApi;
1747}
1748
1749declare const Sinon: Sinon.SinonStatic;
1750
1751export = Sinon;
1752export as namespace sinon;