UNPKG

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