UNPKG

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