UNPKG

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