2 * Sinon.JS 1.17.6, 2016/09/19
4 * @author Christian Johansen (christian@cjohansen.no)
5 * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS
9 * Copyright (c) 2010-2014, Christian Johansen, christian@cjohansen.no
10 * All rights reserved.
12 * Redistribution and use in source and binary forms, with or without modification,
13 * are permitted provided that the following conditions are met:
15 * * Redistributions of source code must retain the above copyright notice,
16 * this list of conditions and the following disclaimer.
17 * * Redistributions in binary form must reproduce the above copyright notice,
18 * this list of conditions and the following disclaimer in the documentation
19 * and/or other materials provided with the distribution.
20 * * Neither the name of Christian Johansen nor the names of his contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
26 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
30 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
32 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 (function (root
, factory
) {
38 if (typeof define
=== 'function' && define
.amd
) {
39 define('sinon', [], function () {
40 return (root
.sinon
= factory());
42 } else if (typeof exports
=== 'object') {
43 module
.exports
= factory();
45 root
.sinon
= factory();
49 var samsam
, formatio
, lolex
;
51 function define(mod
, deps
, fn
) {
52 if (mod
== "samsam") {
54 } else if (typeof deps
=== "function" && mod
.length
=== 0) {
56 } else if (typeof fn
=== "function") {
57 formatio
= fn(samsam
);
61 ((typeof define
=== "function" && define
.amd
&& function (m
) { define("samsam", m
); }) ||
62 (typeof module
=== "object" &&
63 function (m
) { module
.exports
= m(); }) || // Node
64 function (m
) { this.samsam
= m(); } // Browser globals
66 var o
= Object
.prototype;
67 var div
= typeof document
!== "undefined" && document
.createElement("div");
69 function isNaN(value
) {
70 // Unlike global isNaN, this avoids type coercion
71 // typeof check avoids IE host object issues, hat tip to
73 var val
= value
; // JsLint thinks value !== value is "weird"
74 return typeof value
=== "number" && value
!== val
;
77 function getClass(value
) {
78 // Returns the internal [[Class]] by calling Object.prototype.toString
79 // with the provided value as this. Return value is a string, naming the
80 // internal class, e.g. "Array"
81 return o
.toString
.call(value
).split(/[ \]]/)[1];
85 * @name samsam.isArguments
86 * @param Object object
88 * Returns ``true`` if ``object`` is an ``arguments`` object,
89 * ``false`` otherwise.
91 function isArguments(object
) {
92 if (getClass(object
) === 'Arguments') { return true; }
93 if (typeof object
!== "object" || typeof object
.length
!== "number" ||
94 getClass(object
) === "Array") {
97 if (typeof object
.callee
== "function") { return true; }
99 object
[object
.length
] = 6;
100 delete object
[object
.length
];
108 * @name samsam.isElement
109 * @param Object object
111 * Returns ``true`` if ``object`` is a DOM element node. Unlike
112 * Underscore.js/lodash, this function will return ``false`` if ``object``
113 * is an *element-like* object, i.e. a regular object with a ``nodeType``
114 * property that holds the value ``1``.
116 function isElement(object
) {
117 if (!object
|| object
.nodeType
!== 1 || !div
) { return false; }
119 object
.appendChild(div
);
120 object
.removeChild(div
);
129 * @param Object object
131 * Return an array of own property names.
133 function keys(object
) {
135 for (prop
in object
) {
136 if (o
.hasOwnProperty
.call(object
, prop
)) { ks
.push(prop
); }
142 * @name samsam.isDate
143 * @param Object value
145 * Returns true if the object is a ``Date``, or *date-like*. Duck typing
146 * of date objects work by checking that the object has a ``getTime``
147 * function whose return value equals the return value from the object's
150 function isDate(value
) {
151 return typeof value
.getTime
== "function" &&
152 value
.getTime() == value
.valueOf();
156 * @name samsam.isNegZero
157 * @param Object value
159 * Returns ``true`` if ``value`` is ``-0``.
161 function isNegZero(value
) {
162 return value
=== 0 && 1 / value
=== -Infinity
;
170 * Returns ``true`` if two objects are strictly equal. Compared to
171 * ``===`` there are two exceptions:
173 * - NaN is considered equal to NaN
174 * - -0 and +0 are not considered equal
176 function identical(obj1
, obj2
) {
177 if (obj1
=== obj2
|| (isNaN(obj1
) && isNaN(obj2
))) {
178 return obj1
!== 0 || isNegZero(obj1
) === isNegZero(obj2
);
184 * @name samsam.deepEqual
188 * Deep equal comparison. Two values are "deep equal" if:
190 * - They are equal, according to samsam.identical
191 * - They are both date objects representing the same time
192 * - They are both arrays containing elements that are all deepEqual
193 * - They are objects with the same set of properties, and each property
194 * in ``obj1`` is deepEqual to the corresponding property in ``obj2``
196 * Supports cyclic objects.
198 function deepEqualCyclic(obj1
, obj2
) {
200 // used for cyclic comparison
201 // contain already visited objects
204 // contain pathes (position in the object structure)
205 // of the already visited objects
206 // indexes same as in objects arrays
209 // contains combinations of already compared objects
210 // in the manner: { "$1['ref']$2['ref']": true }
214 * used to check, if the value of a property is an object
215 * (cyclic logic is only needed for objects)
216 * only needed for cyclic logic
218 function isObject(value
) {
220 if (typeof value
=== 'object' && value
!== null &&
221 !(value
instanceof Boolean
) &&
222 !(value
instanceof Date
) &&
223 !(value
instanceof Number
) &&
224 !(value
instanceof RegExp
) &&
225 !(value
instanceof String
)) {
234 * returns the index of the given object in the
235 * given objects array, -1 if not contained
236 * only needed for cyclic logic
238 function getIndex(objects
, obj
) {
241 for (i
= 0; i
< objects
.length
; i
++) {
242 if (objects
[i
] === obj
) {
250 // does the recursion for the deep equal check
251 return (function deepEqual(obj1
, obj2
, path1
, path2
) {
252 var type1
= typeof obj1
;
253 var type2
= typeof obj2
;
255 // == null also matches undefined
257 isNaN(obj1
) || isNaN(obj2
) ||
258 obj1
== null || obj2
== null ||
259 type1
!== "object" || type2
!== "object") {
261 return identical(obj1
, obj2
);
264 // Elements are only equal if identical(expected, actual)
265 if (isElement(obj1
) || isElement(obj2
)) { return false; }
267 var isDate1
= isDate(obj1
), isDate2
= isDate(obj2
);
268 if (isDate1
|| isDate2
) {
269 if (!isDate1
|| !isDate2
|| obj1
.getTime() !== obj2
.getTime()) {
274 if (obj1
instanceof RegExp
&& obj2
instanceof RegExp
) {
275 if (obj1
.toString() !== obj2
.toString()) { return false; }
278 var class1
= getClass(obj1
);
279 var class2
= getClass(obj2
);
280 var keys1
= keys(obj1
);
281 var keys2
= keys(obj2
);
283 if (isArguments(obj1
) || isArguments(obj2
)) {
284 if (obj1
.length
!== obj2
.length
) { return false; }
286 if (type1
!== type2
|| class1
!== class2
||
287 keys1
.length
!== keys2
.length
) {
293 // following vars are used for the cyclic logic
295 isObject1
, isObject2
,
299 for (i
= 0, l
= keys1
.length
; i
< l
; i
++) {
301 if (!o
.hasOwnProperty
.call(obj2
, key
)) {
305 // Start of the cyclic logic
310 isObject1
= isObject(value1
);
311 isObject2
= isObject(value2
);
313 // determine, if the objects were already visited
314 // (it's faster to check for isObject first, than to
315 // get -1 from getIndex for non objects)
316 index1
= isObject1
? getIndex(objects1
, value1
) : -1;
317 index2
= isObject2
? getIndex(objects2
, value2
) : -1;
319 // determine the new pathes of the objects
320 // - for non cyclic objects the current path will be extended
321 // by current property name
322 // - for cyclic objects the stored path is taken
323 newPath1
= index1
!== -1
325 : path1
+ '[' + JSON
.stringify(key
) + ']';
326 newPath2
= index2
!== -1
328 : path2
+ '[' + JSON
.stringify(key
) + ']';
330 // stop recursion if current objects are already compared
331 if (compared
[newPath1
+ newPath2
]) {
335 // remember the current objects and their pathes
336 if (index1
=== -1 && isObject1
) {
337 objects1
.push(value1
);
338 paths1
.push(newPath1
);
340 if (index2
=== -1 && isObject2
) {
341 objects2
.push(value2
);
342 paths2
.push(newPath2
);
345 // remember that the current objects are already compared
346 if (isObject1
&& isObject2
) {
347 compared
[newPath1
+ newPath2
] = true;
350 // End of cyclic logic
352 // neither value1 nor value2 is a cycle
353 // continue with next level
354 if (!deepEqual(value1
, value2
, newPath1
, newPath2
)) {
361 }(obj1
, obj2
, '$1', '$2'));
366 function arrayContains(array
, subset
) {
367 if (subset
.length
=== 0) { return true; }
369 for (i
= 0, l
= array
.length
; i
< l
; ++i
) {
370 if (match(array
[i
], subset
[0])) {
371 for (j
= 0, k
= subset
.length
; j
< k
; ++j
) {
372 if (!match(array
[i
+ j
], subset
[j
])) { return false; }
382 * @param Object object
383 * @param Object matcher
385 * Compare arbitrary value ``object`` with matcher.
387 match
= function match(object
, matcher
) {
388 if (matcher
&& typeof matcher
.test
=== "function") {
389 return matcher
.test(object
);
392 if (typeof matcher
=== "function") {
393 return matcher(object
) === true;
396 if (typeof matcher
=== "string") {
397 matcher
= matcher
.toLowerCase();
398 var notNull
= typeof object
=== "string" || !!object
;
400 (String(object
)).toLowerCase().indexOf(matcher
) >= 0;
403 if (typeof matcher
=== "number") {
404 return matcher
=== object
;
407 if (typeof matcher
=== "boolean") {
408 return matcher
=== object
;
411 if (typeof(matcher
) === "undefined") {
412 return typeof(object
) === "undefined";
415 if (matcher
=== null) {
416 return object
=== null;
419 if (getClass(object
) === "Array" && getClass(matcher
) === "Array") {
420 return arrayContains(object
, matcher
);
423 if (matcher
&& typeof matcher
=== "object") {
424 if (matcher
=== object
) {
428 for (prop
in matcher
) {
429 var value
= object
[prop
];
430 if (typeof value
=== "undefined" &&
431 typeof object
.getAttribute
=== "function") {
432 value
= object
.getAttribute(prop
);
434 if (matcher
[prop
] === null || typeof matcher
[prop
] === 'undefined') {
435 if (value
!== matcher
[prop
]) {
438 } else if (typeof value
=== "undefined" || !match(value
, matcher
[prop
])) {
445 throw new Error("Matcher was not a string, a number, a " +
446 "function, a boolean or an object");
450 isArguments
: isArguments
,
451 isElement
: isElement
,
453 isNegZero
: isNegZero
,
454 identical
: identical
,
455 deepEqual
: deepEqualCyclic
,
460 ((typeof define
=== "function" && define
.amd
&& function (m
) {
461 define("formatio", ["samsam"], m
);
462 }) || (typeof module
=== "object" && function (m
) {
463 module
.exports
= m(require("samsam"));
464 }) || function (m
) { this.formatio
= m(this.samsam
); }
465 )(function (samsam
) {
468 excludeConstructors
: ["Object", /^.$/],
470 limitChildrenCount
: 0
473 var hasOwn
= Object
.prototype.hasOwnProperty
;
475 var specialObjects
= [];
476 if (typeof global
!== "undefined") {
477 specialObjects
.push({ object
: global
, value
: "[object global]" });
479 if (typeof document
!== "undefined") {
480 specialObjects
.push({
482 value
: "[object HTMLDocument]"
485 if (typeof window
!== "undefined") {
486 specialObjects
.push({ object
: window
, value
: "[object Window]" });
489 function functionName(func
) {
490 if (!func
) { return ""; }
491 if (func
.displayName
) { return func
.displayName
; }
492 if (func
.name
) { return func
.name
; }
493 var matches
= func
.toString().match(/function\s+([^\(]+)/m);
494 return (matches
&& matches
[1]) || "";
497 function constructorName(f
, object
) {
498 var name
= functionName(object
&& object
.constructor);
499 var excludes
= f
.excludeConstructors
||
500 formatio
.excludeConstructors
|| [];
503 for (i
= 0, l
= excludes
.length
; i
< l
; ++i
) {
504 if (typeof excludes
[i
] === "string" && excludes
[i
] === name
) {
506 } else if (excludes
[i
].test
&& excludes
[i
].test(name
)) {
514 function isCircular(object
, objects
) {
515 if (typeof object
!== "object") { return false; }
517 for (i
= 0, l
= objects
.length
; i
< l
; ++i
) {
518 if (objects
[i
] === object
) { return true; }
523 function ascii(f
, object
, processed
, indent
) {
524 if (typeof object
=== "string") {
525 var qs
= f
.quoteStrings
;
526 var quote
= typeof qs
!== "boolean" || qs
;
527 return processed
|| quote
? '"' + object
+ '"' : object
;
530 if (typeof object
=== "function" && !(object
instanceof RegExp
)) {
531 return ascii
.func(object
);
534 processed
= processed
|| [];
536 if (isCircular(object
, processed
)) { return "[Circular]"; }
538 if (Object
.prototype.toString
.call(object
) === "[object Array]") {
539 return ascii
.array
.call(f
, object
, processed
);
542 if (!object
) { return String((1/object
) === -Infinity
? "-0" : object
); }
543 if (samsam
.isElement(object
)) { return ascii
.element(object
); }
545 if (typeof object
.toString
=== "function" &&
546 object
.toString
!== Object
.prototype.toString
) {
547 return object
.toString();
551 for (i
= 0, l
= specialObjects
.length
; i
< l
; i
++) {
552 if (object
=== specialObjects
[i
].object
) {
553 return specialObjects
[i
].value
;
557 return ascii
.object
.call(f
, object
, processed
, indent
);
560 ascii
.func = function (func
) {
561 return "function " + functionName(func
) + "() {}";
564 ascii
.array = function (array
, processed
) {
565 processed
= processed
|| [];
566 processed
.push(array
);
569 l
= (this.limitChildrenCount
> 0) ?
570 Math
.min(this.limitChildrenCount
, array
.length
) : array
.length
;
572 for (i
= 0; i
< l
; ++i
) {
573 pieces
.push(ascii(this, array
[i
], processed
));
577 pieces
.push("[... " + (array
.length
- l
) + " more elements]");
579 return "[" + pieces
.join(", ") + "]";
582 ascii
.object = function (object
, processed
, indent
) {
583 processed
= processed
|| [];
584 processed
.push(object
);
585 indent
= indent
|| 0;
586 var pieces
= [], properties
= samsam
.keys(object
).sort();
588 var prop
, str
, obj
, i
, k
, l
;
589 l
= (this.limitChildrenCount
> 0) ?
590 Math
.min(this.limitChildrenCount
, properties
.length
) : properties
.length
;
592 for (i
= 0; i
< l
; ++i
) {
593 prop
= properties
[i
];
596 if (isCircular(obj
, processed
)) {
599 str
= ascii(this, obj
, processed
, indent
+ 2);
602 str
= (/\s/.test(prop
) ? '"' + prop
+ '"' : prop
) + ": " + str
;
603 length
+= str
.length
;
607 var cons
= constructorName(this, object
);
608 var prefix
= cons
? "[" + cons
+ "] " : "";
610 for (i
= 0, k
= indent
; i
< k
; ++i
) { is
+= " "; }
612 if(l
< properties
.length
)
613 pieces
.push("[... " + (properties
.length
- l
) + " more elements]");
615 if (length
+ indent
> 80) {
616 return prefix
+ "{\n " + is
+ pieces
.join(",\n " + is
) + "\n" +
619 return prefix
+ "{ " + pieces
.join(", ") + " }";
622 ascii
.element = function (element
) {
623 var tagName
= element
.tagName
.toLowerCase();
624 var attrs
= element
.attributes
, attr
, pairs
= [], attrName
, i
, l
, val
;
626 for (i
= 0, l
= attrs
.length
; i
< l
; ++i
) {
627 attr
= attrs
.item(i
);
628 attrName
= attr
.nodeName
.toLowerCase().replace("html:", "");
629 val
= attr
.nodeValue
;
630 if (attrName
!== "contenteditable" || val
!== "inherit") {
631 if (!!val
) { pairs
.push(attrName
+ "=\"" + val
+ "\""); }
635 var formatted
= "<" + tagName
+ (pairs
.length
> 0 ? " " : "");
636 var content
= element
.innerHTML
;
638 if (content
.length
> 20) {
639 content
= content
.substr(0, 20) + "[...]";
642 var res
= formatted
+ pairs
.join(" ") + ">" + content
+
643 "</" + tagName
+ ">";
645 return res
.replace(/ contentEditable
="inherit"/, "");
648 function Formatio(options
) {
649 for (var opt
in options
) {
650 this[opt
] = options
[opt
];
654 Formatio
.prototype = {
655 functionName
: functionName
,
657 configure: function (options
) {
658 return new Formatio(options
);
661 constructorName: function (object
) {
662 return constructorName(this, object
);
665 ascii: function (object
, processed
, indent
) {
666 return ascii(this, object
, processed
, indent
);
670 return Formatio
.prototype;
672 !function(e
){if("object"==typeof exports
&&"undefined"!=typeof module
)module
.exports
=e();else if("function"==typeof define
&&define
.amd
)define([],e
);else{var f
;"undefined"!=typeof window
?f
=window
:"undefined"!=typeof global
?f
=global
:"undefined"!=typeof self
&&(f
=self
),f
.lolex
=e()}}(function(){var define
,module
,exports
;return (function e(t
,n
,r
){function s(o
,u
){if(!n
[o
]){if(!t
[o
]){var a
=typeof require
=="function"&&require
;if(!u
&&a
)return a(o
,!0);if(i
)return i(o
,!0);var f
=new Error("Cannot find module '"+o
+"'");throw f
.code
="MODULE_NOT_FOUND",f
}var l
=n
[o
]={exports
:{}};t
[o
][0].call(l
.exports
,function(e
){var n
=t
[o
][1][e
];return s(n
?n
:e
)},l
,l
.exports
,e
,t
,n
,r
)}return n
[o
].exports
}var i
=typeof require
=="function"&&require
;for(var o
=0;o
<r
.length
;o
++)s(r
[o
]);return s
})({1:[function(require
,module
,exports
){
674 /*global global, window*/
676 * @author Christian Johansen (christian@cjohansen.no) and contributors
679 * Copyright (c) 2010-2014 Christian Johansen
684 // Make properties writable in IE, as per
685 // http://www.adequatelygood.com/Replacing-setTimeout-Globally.html
689 global
.setTimeout
= glbl
.setTimeout
;
690 global
.clearTimeout
= glbl
.clearTimeout
;
691 global
.setInterval
= glbl
.setInterval
;
692 global
.clearInterval
= glbl
.clearInterval
;
693 global
.Date
= glbl
.Date
;
695 // setImmediate is not a standard function
696 // avoid adding the prop to the window object if not present
697 if('setImmediate' in global
) {
698 global
.setImmediate
= glbl
.setImmediate
;
699 global
.clearImmediate
= glbl
.clearImmediate
;
702 // node expects setTimeout/setInterval to return a fn object w/ .ref()/.unref()
703 // browsers, a number.
704 // see https://github.com/cjohansen/Sinon.JS/pull/436
706 var NOOP = function () { return undefined; };
707 var timeoutResult
= setTimeout(NOOP
, 0);
708 var addTimerReturnsObject
= typeof timeoutResult
=== "object";
709 clearTimeout(timeoutResult
);
711 var NativeDate
= Date
;
712 var uniqueTimerId
= 1;
715 * Parse strings like "01:10:00" (meaning 1 hour, 10 minutes, 0 seconds) into
716 * number of milliseconds. This is used to support human-readable strings passed
719 function parseTime(str
) {
724 var strings
= str
.split(":");
725 var l
= strings
.length
, i
= l
;
728 if (l
> 3 || !/^(\d\d:){0,2}\d\d?$/.test(str
)) {
729 throw new Error("tick only understands numbers and 'h:m:s'");
733 parsed
= parseInt(strings
[i
], 10);
736 throw new Error("Invalid time " + str
);
739 ms
+= parsed
* Math
.pow(60, (l
- i
- 1));
746 * Used to grok the `now` parameter to createClock.
748 function getEpoch(epoch
) {
749 if (!epoch
) { return 0; }
750 if (typeof epoch
.getTime
=== "function") { return epoch
.getTime(); }
751 if (typeof epoch
=== "number") { return epoch
; }
752 throw new TypeError("now should be milliseconds since UNIX epoch");
755 function inRange(from, to
, timer
) {
756 return timer
&& timer
.callAt
>= from && timer
.callAt
<= to
;
759 function mirrorDateProperties(target
, source
) {
761 for (prop
in source
) {
762 if (source
.hasOwnProperty(prop
)) {
763 target
[prop
] = source
[prop
];
767 // set special now implementation
769 target
.now
= function now() {
770 return target
.clock
.now
;
776 // set special toSource implementation
777 if (source
.toSource
) {
778 target
.toSource
= function toSource() {
779 return source
.toSource();
782 delete target
.toSource
;
785 // set special toString implementation
786 target
.toString
= function toString() {
787 return source
.toString();
790 target
.prototype = source
.prototype;
791 target
.parse
= source
.parse
;
792 target
.UTC
= source
.UTC
;
793 target
.prototype.toUTCString
= source
.prototype.toUTCString
;
798 function createDate() {
799 function ClockDate(year
, month
, date
, hour
, minute
, second
, ms
) {
800 // Defensive and verbose to avoid potential harm in passing
801 // explicit undefined when user does not pass argument
802 switch (arguments
.length
) {
804 return new NativeDate(ClockDate
.clock
.now
);
806 return new NativeDate(year
);
808 return new NativeDate(year
, month
);
810 return new NativeDate(year
, month
, date
);
812 return new NativeDate(year
, month
, date
, hour
);
814 return new NativeDate(year
, month
, date
, hour
, minute
);
816 return new NativeDate(year
, month
, date
, hour
, minute
, second
);
818 return new NativeDate(year
, month
, date
, hour
, minute
, second
, ms
);
822 return mirrorDateProperties(ClockDate
, NativeDate
);
825 function addTimer(clock
, timer
) {
826 if (timer
.func
=== undefined) {
827 throw new Error("Callback must be provided to timer calls");
834 timer
.id
= uniqueTimerId
++;
835 timer
.createdAt
= clock
.now
;
836 timer
.callAt
= clock
.now
+ (timer
.delay
|| (clock
.duringTick
? 1 : 0));
838 clock
.timers
[timer
.id
] = timer
;
840 if (addTimerReturnsObject
) {
852 function compareTimers(a
, b
) {
853 // Sort first by absolute timing
854 if (a
.callAt
< b
.callAt
) {
857 if (a
.callAt
> b
.callAt
) {
861 // Sort next by immediate, immediate timers take precedence
862 if (a
.immediate
&& !b
.immediate
) {
865 if (!a
.immediate
&& b
.immediate
) {
869 // Sort next by creation time, earlier-created timers take precedence
870 if (a
.createdAt
< b
.createdAt
) {
873 if (a
.createdAt
> b
.createdAt
) {
877 // Sort next by id, lower-id timers take precedence
885 // As timer ids are unique, no fallback `0` is necessary
888 function firstTimerInRange(clock
, from, to
) {
889 var timers
= clock
.timers
,
895 if (timers
.hasOwnProperty(id
)) {
896 isInRange
= inRange(from, to
, timers
[id
]);
898 if (isInRange
&& (!timer
|| compareTimers(timer
, timers
[id
]) === 1)) {
907 function callTimer(clock
, timer
) {
910 if (typeof timer
.interval
=== "number") {
911 clock
.timers
[timer
.id
].callAt
+= timer
.interval
;
913 delete clock
.timers
[timer
.id
];
917 if (typeof timer
.func
=== "function") {
918 timer
.func
.apply(null, timer
.args
);
926 if (!clock
.timers
[timer
.id
]) {
938 function timerType(timer
) {
939 if (timer
.immediate
) {
941 } else if (typeof timer
.interval
!== "undefined") {
948 function clearTimer(clock
, timerId
, ttype
) {
950 // null appears to be allowed in most browsers, and appears to be
951 // relied upon by some libraries, like Bootstrap carousel
959 // in Node, timerId is an object with .ref()/.unref(), and
960 // its .id field is the actual timer id.
961 if (typeof timerId
=== "object") {
962 timerId
= timerId
.id
;
965 if (clock
.timers
.hasOwnProperty(timerId
)) {
966 // check that the ID matches a timer of the correct type
967 var timer
= clock
.timers
[timerId
];
968 if (timerType(timer
) === ttype
) {
969 delete clock
.timers
[timerId
];
971 throw new Error("Cannot clear timer: timer created with set" + ttype
+ "() but cleared with clear" + timerType(timer
) + "()");
976 function uninstall(clock
, target
) {
981 for (i
= 0, l
= clock
.methods
.length
; i
< l
; i
++) {
982 method
= clock
.methods
[i
];
984 if (target
[method
].hadOwnProperty
) {
985 target
[method
] = clock
["_" + method
];
988 delete target
[method
];
993 // Prevent multiple executions which will completely remove these props
997 function hijackMethod(target
, method
, clock
) {
1000 clock
[method
].hadOwnProperty
= Object
.prototype.hasOwnProperty
.call(target
, method
);
1001 clock
["_" + method
] = target
[method
];
1003 if (method
=== "Date") {
1004 var date
= mirrorDateProperties(clock
[method
], target
[method
]);
1005 target
[method
] = date
;
1007 target
[method
] = function () {
1008 return clock
[method
].apply(clock
, arguments
);
1011 for (prop
in clock
[method
]) {
1012 if (clock
[method
].hasOwnProperty(prop
)) {
1013 target
[method
][prop
] = clock
[method
][prop
];
1018 target
[method
].clock
= clock
;
1022 setTimeout
: setTimeout
,
1023 clearTimeout
: clearTimeout
,
1024 setImmediate
: global
.setImmediate
,
1025 clearImmediate
: global
.clearImmediate
,
1026 setInterval
: setInterval
,
1027 clearInterval
: clearInterval
,
1031 var keys
= Object
.keys
|| function (obj
) {
1036 if (obj
.hasOwnProperty(key
)) {
1044 exports
.timers
= timers
;
1046 function createClock(now
) {
1053 clock
.Date
.clock
= clock
;
1055 clock
.setTimeout
= function setTimeout(func
, timeout
) {
1056 return addTimer(clock
, {
1058 args
: Array
.prototype.slice
.call(arguments
, 2),
1063 clock
.clearTimeout
= function clearTimeout(timerId
) {
1064 return clearTimer(clock
, timerId
, "Timeout");
1067 clock
.setInterval
= function setInterval(func
, timeout
) {
1068 return addTimer(clock
, {
1070 args
: Array
.prototype.slice
.call(arguments
, 2),
1076 clock
.clearInterval
= function clearInterval(timerId
) {
1077 return clearTimer(clock
, timerId
, "Interval");
1080 clock
.setImmediate
= function setImmediate(func
) {
1081 return addTimer(clock
, {
1083 args
: Array
.prototype.slice
.call(arguments
, 1),
1088 clock
.clearImmediate
= function clearImmediate(timerId
) {
1089 return clearTimer(clock
, timerId
, "Immediate");
1092 clock
.tick
= function tick(ms
) {
1093 ms
= typeof ms
=== "number" ? ms
: parseTime(ms
);
1094 var tickFrom
= clock
.now
, tickTo
= clock
.now
+ ms
, previous
= clock
.now
;
1095 var timer
= firstTimerInRange(clock
, tickFrom
, tickTo
);
1098 clock
.duringTick
= true;
1101 while (timer
&& tickFrom
<= tickTo
) {
1102 if (clock
.timers
[timer
.id
]) {
1103 tickFrom
= clock
.now
= timer
.callAt
;
1106 callTimer(clock
, timer
);
1107 // compensate for any setSystemTime() call during timer callback
1108 if (oldNow
!== clock
.now
) {
1109 tickFrom
+= clock
.now
- oldNow
;
1110 tickTo
+= clock
.now
- oldNow
;
1111 previous
+= clock
.now
- oldNow
;
1114 firstException
= firstException
|| e
;
1118 timer
= firstTimerInRange(clock
, previous
, tickTo
);
1119 previous
= tickFrom
;
1122 clock
.duringTick
= false;
1125 if (firstException
) {
1126 throw firstException
;
1132 clock
.reset
= function reset() {
1136 clock
.setSystemTime
= function setSystemTime(now
) {
1137 // determine time difference
1138 var newNow
= getEpoch(now
);
1139 var difference
= newNow
- clock
.now
;
1141 // update 'system clock'
1144 // update timers and intervals to keep them stable
1145 for (var id
in clock
.timers
) {
1146 if (clock
.timers
.hasOwnProperty(id
)) {
1147 var timer
= clock
.timers
[id
];
1148 timer
.createdAt
+= difference
;
1149 timer
.callAt
+= difference
;
1156 exports
.createClock
= createClock
;
1158 exports
.install
= function install(target
, now
, toFake
) {
1162 if (typeof target
=== "number") {
1172 var clock
= createClock(now
);
1174 clock
.uninstall = function () {
1175 uninstall(clock
, target
);
1178 clock
.methods
= toFake
|| [];
1180 if (clock
.methods
.length
=== 0) {
1181 clock
.methods
= keys(timers
);
1184 for (i
= 0, l
= clock
.methods
.length
; i
< l
; i
++) {
1185 hijackMethod(target
, clock
.methods
[i
], clock
);
1193 }).call(this,typeof global
!== "undefined" ? global
: typeof self
!== "undefined" ? self
: typeof window
!== "undefined" ? window
: {})
1199 * Sinon core utilities. For internal use only.
1201 * @author Christian Johansen (christian@cjohansen.no)
1204 * Copyright (c) 2010-2013 Christian Johansen
1206 var sinon
= (function () {
1208 // eslint-disable-line no-unused-vars
1211 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
1212 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
1214 function loadDependencies(require
, exports
, module
) {
1215 sinonModule
= module
.exports
= require("./sinon/util/core");
1216 require("./sinon/extend");
1217 require("./sinon/walk");
1218 require("./sinon/typeOf");
1219 require("./sinon/times_in_words");
1220 require("./sinon/spy");
1221 require("./sinon/call");
1222 require("./sinon/behavior");
1223 require("./sinon/stub");
1224 require("./sinon/mock");
1225 require("./sinon/collection");
1226 require("./sinon/assert");
1227 require("./sinon/sandbox");
1228 require("./sinon/test");
1229 require("./sinon/test_case");
1230 require("./sinon/match");
1231 require("./sinon/format");
1232 require("./sinon/log_error");
1236 define(loadDependencies
);
1237 } else if (isNode
) {
1238 loadDependencies(require
, module
.exports
, module
);
1239 sinonModule
= module
.exports
;
1248 * @depend ../../sinon.js
1251 * Sinon core utilities. For internal use only.
1253 * @author Christian Johansen (christian@cjohansen.no)
1256 * Copyright (c) 2010-2013 Christian Johansen
1258 (function (sinonGlobal
) {
1260 var div
= typeof document
!== "undefined" && document
.createElement("div");
1261 var hasOwn
= Object
.prototype.hasOwnProperty
;
1263 function isDOMNode(obj
) {
1264 var success
= false;
1267 obj
.appendChild(div
);
1268 success
= div
.parentNode
=== obj
;
1273 obj
.removeChild(div
);
1275 // Remove failed, not much we can do about that
1282 function isElement(obj
) {
1283 return div
&& obj
&& obj
.nodeType
=== 1 && isDOMNode(obj
);
1286 function isFunction(obj
) {
1287 return typeof obj
=== "function" || !!(obj
&& obj
.constructor && obj
.call
&& obj
.apply
);
1290 function isReallyNaN(val
) {
1291 return typeof val
=== "number" && isNaN(val
);
1294 function mirrorProperties(target
, source
) {
1295 for (var prop
in source
) {
1296 if (!hasOwn
.call(target
, prop
)) {
1297 target
[prop
] = source
[prop
];
1302 function isRestorable(obj
) {
1303 return typeof obj
=== "function" && typeof obj
.restore
=== "function" && obj
.restore
.sinon
;
1306 // Cheap way to detect if we have ES5 support.
1307 var hasES5Support
= "keys" in Object
;
1309 function makeApi(sinon
) {
1310 sinon
.wrapMethod
= function wrapMethod(object
, property
, method
) {
1312 throw new TypeError("Should wrap property of object");
1315 if (typeof method
!== "function" && typeof method
!== "object") {
1316 throw new TypeError("Method wrapper should be a function or a property descriptor");
1319 function checkWrappedMethod(wrappedMethod
) {
1322 if (!isFunction(wrappedMethod
)) {
1323 error
= new TypeError("Attempted to wrap " + (typeof wrappedMethod
) + " property " +
1324 property
+ " as function");
1325 } else if (wrappedMethod
.restore
&& wrappedMethod
.restore
.sinon
) {
1326 error
= new TypeError("Attempted to wrap " + property
+ " which is already wrapped");
1327 } else if (wrappedMethod
.calledBefore
) {
1328 var verb
= wrappedMethod
.returns
? "stubbed" : "spied on";
1329 error
= new TypeError("Attempted to wrap " + property
+ " which is already " + verb
);
1333 if (wrappedMethod
&& wrappedMethod
.stackTrace
) {
1334 error
.stack
+= "\n--------------\n" + wrappedMethod
.stackTrace
;
1340 var error
, wrappedMethod
, i
;
1342 function simplePropertyAssignment() {
1343 wrappedMethod
= object
[property
];
1344 checkWrappedMethod(wrappedMethod
);
1345 object
[property
] = method
;
1346 method
.displayName
= property
;
1349 // IE 8 does not support hasOwnProperty on the window object and Firefox has a problem
1350 // when using hasOwn.call on objects from other frames.
1351 var owned
= object
.hasOwnProperty
? object
.hasOwnProperty(property
) : hasOwn
.call(object
, property
);
1353 if (hasES5Support
) {
1354 var methodDesc
= (typeof method
=== "function") ? {value
: method
} : method
;
1355 var wrappedMethodDesc
= sinon
.getPropertyDescriptor(object
, property
);
1357 if (!wrappedMethodDesc
) {
1358 error
= new TypeError("Attempted to wrap " + (typeof wrappedMethod
) + " property " +
1359 property
+ " as function");
1360 } else if (wrappedMethodDesc
.restore
&& wrappedMethodDesc
.restore
.sinon
) {
1361 error
= new TypeError("Attempted to wrap " + property
+ " which is already wrapped");
1364 if (wrappedMethodDesc
&& wrappedMethodDesc
.stackTrace
) {
1365 error
.stack
+= "\n--------------\n" + wrappedMethodDesc
.stackTrace
;
1370 var types
= sinon
.objectKeys(methodDesc
);
1371 for (i
= 0; i
< types
.length
; i
++) {
1372 wrappedMethod
= wrappedMethodDesc
[types
[i
]];
1373 checkWrappedMethod(wrappedMethod
);
1376 mirrorProperties(methodDesc
, wrappedMethodDesc
);
1377 for (i
= 0; i
< types
.length
; i
++) {
1378 mirrorProperties(methodDesc
[types
[i
]], wrappedMethodDesc
[types
[i
]]);
1380 Object
.defineProperty(object
, property
, methodDesc
);
1382 // catch failing assignment
1383 // this is the converse of the check in `.restore` below
1384 if ( typeof method
=== "function" && object
[property
] !== method
) {
1385 // correct any wrongdoings caused by the defineProperty call above,
1386 // such as adding new items (if object was a Storage object)
1387 delete object
[property
];
1388 simplePropertyAssignment();
1391 simplePropertyAssignment();
1394 method
.displayName
= property
;
1396 // Set up a stack trace which can be used later to find what line of
1397 // code the original method was created on.
1398 method
.stackTrace
= (new Error("Stack Trace for original")).stack
;
1400 method
.restore = function () {
1401 // For prototype properties try to reset by delete first.
1402 // If this fails (ex: localStorage on mobile safari) then force a reset
1403 // via direct assignment.
1405 // In some cases `delete` may throw an error
1407 delete object
[property
];
1408 } catch (e
) {} // eslint-disable-line no-empty
1409 // For native code functions `delete` fails without throwing an error
1410 // on Chrome < 43, PhantomJS, etc.
1411 } else if (hasES5Support
) {
1412 Object
.defineProperty(object
, property
, wrappedMethodDesc
);
1415 // Use strict equality comparison to check failures then force a reset
1416 // via direct assignment.
1417 if (object
[property
] === method
) {
1418 object
[property
] = wrappedMethod
;
1422 method
.restore
.sinon
= true;
1424 if (!hasES5Support
) {
1425 mirrorProperties(method
, wrappedMethod
);
1431 sinon
.create
= function create(proto
) {
1432 var F = function () {};
1433 F
.prototype = proto
;
1437 sinon
.deepEqual
= function deepEqual(a
, b
) {
1438 if (sinon
.match
&& sinon
.match
.isMatcher(a
)) {
1442 if (typeof a
!== "object" || typeof b
!== "object") {
1443 return isReallyNaN(a
) && isReallyNaN(b
) || a
=== b
;
1446 if (isElement(a
) || isElement(b
)) {
1454 if ((a
=== null && b
!== null) || (a
!== null && b
=== null)) {
1458 if (a
instanceof RegExp
&& b
instanceof RegExp
) {
1459 return (a
.source
=== b
.source
) && (a
.global
=== b
.global
) &&
1460 (a
.ignoreCase
=== b
.ignoreCase
) && (a
.multiline
=== b
.multiline
);
1463 var aString
= Object
.prototype.toString
.call(a
);
1464 if (aString
!== Object
.prototype.toString
.call(b
)) {
1468 if (aString
=== "[object Date]") {
1469 return a
.valueOf() === b
.valueOf();
1476 if (aString
=== "[object Array]" && a
.length
!== b
.length
) {
1481 if (hasOwn
.call(a
, prop
)) {
1488 if (!deepEqual(a
[prop
], b
[prop
])) {
1495 if (hasOwn
.call(b
, prop
)) {
1500 return aLength
=== bLength
;
1503 sinon
.functionName
= function functionName(func
) {
1504 var name
= func
.displayName
|| func
.name
;
1506 // Use function decomposition as a last resort to get function
1507 // name. Does not rely on function decomposition to work - if it
1508 // doesn't debugging will be slightly less informative
1509 // (i.e. toString will say 'spy' rather than 'myFunc').
1511 var matches
= func
.toString().match(/function ([^\s\(]+)/);
1512 name
= matches
&& matches
[1];
1518 sinon
.functionToString
= function toString() {
1519 if (this.getCall
&& this.callCount
) {
1522 var i
= this.callCount
;
1525 thisValue
= this.getCall(i
).thisValue
;
1527 for (prop
in thisValue
) {
1528 if (thisValue
[prop
] === this) {
1535 return this.displayName
|| "sinon fake";
1538 sinon
.objectKeys
= function objectKeys(obj
) {
1539 if (obj
!== Object(obj
)) {
1540 throw new TypeError("sinon.objectKeys called on a non-object");
1546 if (hasOwn
.call(obj
, key
)) {
1554 sinon
.getPropertyDescriptor
= function getPropertyDescriptor(object
, property
) {
1558 while (proto
&& !(descriptor
= Object
.getOwnPropertyDescriptor(proto
, property
))) {
1559 proto
= Object
.getPrototypeOf(proto
);
1564 sinon
.getConfig = function (custom
) {
1566 custom
= custom
|| {};
1567 var defaults
= sinon
.defaultConfig
;
1569 for (var prop
in defaults
) {
1570 if (defaults
.hasOwnProperty(prop
)) {
1571 config
[prop
] = custom
.hasOwnProperty(prop
) ? custom
[prop
] : defaults
[prop
];
1578 sinon
.defaultConfig
= {
1579 injectIntoThis
: true,
1581 properties
: ["spy", "stub", "mock", "clock", "server", "requests"],
1582 useFakeTimers
: true,
1586 sinon
.timesInWords
= function timesInWords(count
) {
1587 return count
=== 1 && "once" ||
1588 count
=== 2 && "twice" ||
1589 count
=== 3 && "thrice" ||
1590 (count
|| 0) + " times";
1593 sinon
.calledInOrder = function (spies
) {
1594 for (var i
= 1, l
= spies
.length
; i
< l
; i
++) {
1595 if (!spies
[i
- 1].calledBefore(spies
[i
]) || !spies
[i
].called
) {
1603 sinon
.orderByFirstCall = function (spies
) {
1604 return spies
.sort(function (a
, b
) {
1605 // uuid, won't ever be equal
1606 var aCall
= a
.getCall(0);
1607 var bCall
= b
.getCall(0);
1608 var aId
= aCall
&& aCall
.callId
|| -1;
1609 var bId
= bCall
&& bCall
.callId
|| -1;
1611 return aId
< bId
? -1 : 1;
1615 sinon
.createStubInstance = function (constructor) {
1616 if (typeof constructor !== "function") {
1617 throw new TypeError("The constructor should be a function.");
1619 return sinon
.stub(sinon
.create(constructor.prototype));
1622 sinon
.restore = function (object
) {
1623 if (object
!== null && typeof object
=== "object") {
1624 for (var prop
in object
) {
1625 if (isRestorable(object
[prop
])) {
1626 object
[prop
].restore();
1629 } else if (isRestorable(object
)) {
1637 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
1638 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
1640 function loadDependencies(require
, exports
) {
1645 define(loadDependencies
);
1650 loadDependencies(require
, module
.exports
, module
);
1655 makeApi(sinonGlobal
);
1658 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
1662 * @depend util/core.js
1664 (function (sinonGlobal
) {
1666 function makeApi(sinon
) {
1668 // Adapted from https://developer.mozilla.org/en/docs/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug
1669 var hasDontEnumBug
= (function () {
1671 constructor: function () {
1674 toString: function () {
1677 valueOf: function () {
1680 toLocaleString: function () {
1683 prototype: function () {
1686 isPrototypeOf: function () {
1689 propertyIsEnumerable: function () {
1692 hasOwnProperty: function () {
1695 length: function () {
1698 unique: function () {
1704 for (var prop
in obj
) {
1705 if (obj
.hasOwnProperty(prop
)) {
1706 result
.push(obj
[prop
]());
1709 return result
.join("") !== "0123456789";
1712 /* Public: Extend target in place with all (own) properties from sources in-order. Thus, last source will
1713 * override properties in previous sources.
1715 * target - The Object to extend
1716 * sources - Objects to copy properties from.
1718 * Returns the extended target
1720 function extend(target
/*, sources */) {
1721 var sources
= Array
.prototype.slice
.call(arguments
, 1);
1722 var source
, i
, prop
;
1724 for (i
= 0; i
< sources
.length
; i
++) {
1725 source
= sources
[i
];
1727 for (prop
in source
) {
1728 if (source
.hasOwnProperty(prop
)) {
1729 target
[prop
] = source
[prop
];
1733 // Make sure we copy (own) toString method even when in JScript with DontEnum bug
1734 // See https://developer.mozilla.org/en/docs/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug
1735 if (hasDontEnumBug
&& source
.hasOwnProperty("toString") && source
.toString
!== target
.toString
) {
1736 target
.toString
= source
.toString
;
1743 sinon
.extend
= extend
;
1744 return sinon
.extend
;
1747 function loadDependencies(require
, exports
, module
) {
1748 var sinon
= require("./util/core");
1749 module
.exports
= makeApi(sinon
);
1752 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
1753 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
1756 define(loadDependencies
);
1761 loadDependencies(require
, module
.exports
, module
);
1766 makeApi(sinonGlobal
);
1769 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
1773 * @depend util/core.js
1775 (function (sinonGlobal
) {
1777 function makeApi(sinon
) {
1779 function timesInWords(count
) {
1788 return (count
|| 0) + " times";
1792 sinon
.timesInWords
= timesInWords
;
1793 return sinon
.timesInWords
;
1796 function loadDependencies(require
, exports
, module
) {
1797 var core
= require("./util/core");
1798 module
.exports
= makeApi(core
);
1801 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
1802 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
1805 define(loadDependencies
);
1810 loadDependencies(require
, module
.exports
, module
);
1815 makeApi(sinonGlobal
);
1818 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
1822 * @depend util/core.js
1827 * @author Christian Johansen (christian@cjohansen.no)
1830 * Copyright (c) 2010-2014 Christian Johansen
1832 (function (sinonGlobal
) {
1834 function makeApi(sinon
) {
1835 function typeOf(value
) {
1836 if (value
=== null) {
1838 } else if (value
=== undefined) {
1841 var string
= Object
.prototype.toString
.call(value
);
1842 return string
.substring(8, string
.length
- 1).toLowerCase();
1845 sinon
.typeOf
= typeOf
;
1846 return sinon
.typeOf
;
1849 function loadDependencies(require
, exports
, module
) {
1850 var core
= require("./util/core");
1851 module
.exports
= makeApi(core
);
1854 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
1855 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
1858 define(loadDependencies
);
1863 loadDependencies(require
, module
.exports
, module
);
1868 makeApi(sinonGlobal
);
1871 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
1875 * @depend util/core.js
1878 /*jslint eqeqeq: false, onevar: false, plusplus: false*/
1879 /*global module, require, sinon*/
1883 * @author Maximilian Antoni (mail@maxantoni.de)
1886 * Copyright (c) 2012 Maximilian Antoni
1888 (function (sinonGlobal
) {
1890 function makeApi(sinon
) {
1891 function assertType(value
, type
, name
) {
1892 var actual
= sinon
.typeOf(value
);
1893 if (actual
!== type
) {
1894 throw new TypeError("Expected type of " + name
+ " to be " +
1895 type
+ ", but was " + actual
);
1900 toString: function () {
1901 return this.message
;
1905 function isMatcher(object
) {
1906 return matcher
.isPrototypeOf(object
);
1909 function matchObject(expectation
, actual
) {
1910 if (actual
=== null || actual
=== undefined) {
1913 for (var key
in expectation
) {
1914 if (expectation
.hasOwnProperty(key
)) {
1915 var exp
= expectation
[key
];
1916 var act
= actual
[key
];
1917 if (isMatcher(exp
)) {
1918 if (!exp
.test(act
)) {
1921 } else if (sinon
.typeOf(exp
) === "object") {
1922 if (!matchObject(exp
, act
)) {
1925 } else if (!sinon
.deepEqual(exp
, act
)) {
1933 function match(expectation
, message
) {
1934 var m
= sinon
.create(matcher
);
1935 var type
= sinon
.typeOf(expectation
);
1938 if (typeof expectation
.test
=== "function") {
1939 m
.test = function (actual
) {
1940 return expectation
.test(actual
) === true;
1942 m
.message
= "match(" + sinon
.functionName(expectation
.test
) + ")";
1946 for (var key
in expectation
) {
1947 if (expectation
.hasOwnProperty(key
)) {
1948 str
.push(key
+ ": " + expectation
[key
]);
1951 m
.test = function (actual
) {
1952 return matchObject(expectation
, actual
);
1954 m
.message
= "match(" + str
.join(", ") + ")";
1957 m
.test = function (actual
) {
1958 // we need type coercion here
1959 return expectation
== actual
; // eslint-disable-line eqeqeq
1963 m
.test = function (actual
) {
1964 if (typeof actual
!== "string") {
1967 return actual
.indexOf(expectation
) !== -1;
1969 m
.message
= "match(\"" + expectation
+ "\")";
1972 m
.test = function (actual
) {
1973 if (typeof actual
!== "string") {
1976 return expectation
.test(actual
);
1980 m
.test
= expectation
;
1982 m
.message
= message
;
1984 m
.message
= "match(" + sinon
.functionName(expectation
) + ")";
1988 m
.test = function (actual
) {
1989 return sinon
.deepEqual(expectation
, actual
);
1993 m
.message
= "match(" + expectation
+ ")";
1998 matcher
.or = function (m2
) {
1999 if (!arguments
.length
) {
2000 throw new TypeError("Matcher expected");
2001 } else if (!isMatcher(m2
)) {
2005 var or
= sinon
.create(matcher
);
2006 or
.test = function (actual
) {
2007 return m1
.test(actual
) || m2
.test(actual
);
2009 or
.message
= m1
.message
+ ".or(" + m2
.message
+ ")";
2013 matcher
.and = function (m2
) {
2014 if (!arguments
.length
) {
2015 throw new TypeError("Matcher expected");
2016 } else if (!isMatcher(m2
)) {
2020 var and
= sinon
.create(matcher
);
2021 and
.test = function (actual
) {
2022 return m1
.test(actual
) && m2
.test(actual
);
2024 and
.message
= m1
.message
+ ".and(" + m2
.message
+ ")";
2028 match
.isMatcher
= isMatcher
;
2030 match
.any
= match(function () {
2034 match
.defined
= match(function (actual
) {
2035 return actual
!== null && actual
!== undefined;
2038 match
.truthy
= match(function (actual
) {
2042 match
.falsy
= match(function (actual
) {
2046 match
.same = function (expectation
) {
2047 return match(function (actual
) {
2048 return expectation
=== actual
;
2049 }, "same(" + expectation
+ ")");
2052 match
.typeOf = function (type
) {
2053 assertType(type
, "string", "type");
2054 return match(function (actual
) {
2055 return sinon
.typeOf(actual
) === type
;
2056 }, "typeOf(\"" + type
+ "\")");
2059 match
.instanceOf = function (type
) {
2060 assertType(type
, "function", "type");
2061 return match(function (actual
) {
2062 return actual
instanceof type
;
2063 }, "instanceOf(" + sinon
.functionName(type
) + ")");
2066 function createPropertyMatcher(propertyTest
, messagePrefix
) {
2067 return function (property
, value
) {
2068 assertType(property
, "string", "property");
2069 var onlyProperty
= arguments
.length
=== 1;
2070 var message
= messagePrefix
+ "(\"" + property
+ "\"";
2071 if (!onlyProperty
) {
2072 message
+= ", " + value
;
2075 return match(function (actual
) {
2076 if (actual
=== undefined || actual
=== null ||
2077 !propertyTest(actual
, property
)) {
2080 return onlyProperty
|| sinon
.deepEqual(value
, actual
[property
]);
2085 match
.has
= createPropertyMatcher(function (actual
, property
) {
2086 if (typeof actual
=== "object") {
2087 return property
in actual
;
2089 return actual
[property
] !== undefined;
2092 match
.hasOwn
= createPropertyMatcher(function (actual
, property
) {
2093 return actual
.hasOwnProperty(property
);
2096 match
.bool
= match
.typeOf("boolean");
2097 match
.number
= match
.typeOf("number");
2098 match
.string
= match
.typeOf("string");
2099 match
.object
= match
.typeOf("object");
2100 match
.func
= match
.typeOf("function");
2101 match
.array
= match
.typeOf("array");
2102 match
.regexp
= match
.typeOf("regexp");
2103 match
.date
= match
.typeOf("date");
2105 sinon
.match
= match
;
2109 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
2110 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
2112 function loadDependencies(require
, exports
, module
) {
2113 var sinon
= require("./util/core");
2114 require("./typeOf");
2115 module
.exports
= makeApi(sinon
);
2119 define(loadDependencies
);
2124 loadDependencies(require
, module
.exports
, module
);
2129 makeApi(sinonGlobal
);
2132 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
2136 * @depend util/core.js
2141 * @author Christian Johansen (christian@cjohansen.no)
2144 * Copyright (c) 2010-2014 Christian Johansen
2146 (function (sinonGlobal
, formatio
) {
2148 function makeApi(sinon
) {
2149 function valueFormatter(value
) {
2153 function getFormatioFormatter() {
2154 var formatter
= formatio
.configure({
2155 quoteStrings
: false,
2156 limitChildrenCount
: 250
2160 return formatter
.ascii
.apply(formatter
, arguments
);
2166 function getNodeFormatter() {
2168 var util
= require("util");
2170 /* Node, but no util module - would be very old, but better safe than sorry */
2173 function format(v
) {
2174 var isObjectWithNativeToString
= typeof v
=== "object" && v
.toString
=== Object
.prototype.toString
;
2175 return isObjectWithNativeToString
? util
.inspect(v
) : v
;
2178 return util
? format
: valueFormatter
;
2181 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
2186 formatio
= require("formatio");
2188 catch (e
) {} // eslint-disable-line no-empty
2192 formatter
= getFormatioFormatter();
2193 } else if (isNode
) {
2194 formatter
= getNodeFormatter();
2196 formatter
= valueFormatter
;
2199 sinon
.format
= formatter
;
2200 return sinon
.format
;
2203 function loadDependencies(require
, exports
, module
) {
2204 var sinon
= require("./util/core");
2205 module
.exports
= makeApi(sinon
);
2208 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
2209 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
2212 define(loadDependencies
);
2217 loadDependencies(require
, module
.exports
, module
);
2222 makeApi(sinonGlobal
);
2225 typeof sinon
=== "object" && sinon
, // eslint-disable-line no-undef
2226 typeof formatio
=== "object" && formatio
// eslint-disable-line no-undef
2230 * @depend util/core.js
2237 * @author Christian Johansen (christian@cjohansen.no)
2238 * @author Maximilian Antoni (mail@maxantoni.de)
2241 * Copyright (c) 2010-2013 Christian Johansen
2242 * Copyright (c) 2013 Maximilian Antoni
2244 (function (sinonGlobal
) {
2246 var slice
= Array
.prototype.slice
;
2248 function makeApi(sinon
) {
2249 function throwYieldError(proxy
, text
, args
) {
2250 var msg
= sinon
.functionName(proxy
) + text
;
2252 msg
+= " Received [" + slice
.call(args
).join(", ") + "]";
2254 throw new Error(msg
);
2258 calledOn
: function calledOn(thisValue
) {
2259 if (sinon
.match
&& sinon
.match
.isMatcher(thisValue
)) {
2260 return thisValue
.test(this.thisValue
);
2262 return this.thisValue
=== thisValue
;
2265 calledWith
: function calledWith() {
2266 var l
= arguments
.length
;
2267 if (l
> this.args
.length
) {
2270 for (var i
= 0; i
< l
; i
+= 1) {
2271 if (!sinon
.deepEqual(arguments
[i
], this.args
[i
])) {
2279 calledWithMatch
: function calledWithMatch() {
2280 var l
= arguments
.length
;
2281 if (l
> this.args
.length
) {
2284 for (var i
= 0; i
< l
; i
+= 1) {
2285 var actual
= this.args
[i
];
2286 var expectation
= arguments
[i
];
2287 if (!sinon
.match
|| !sinon
.match(expectation
).test(actual
)) {
2294 calledWithExactly
: function calledWithExactly() {
2295 return arguments
.length
=== this.args
.length
&&
2296 this.calledWith
.apply(this, arguments
);
2299 notCalledWith
: function notCalledWith() {
2300 return !this.calledWith
.apply(this, arguments
);
2303 notCalledWithMatch
: function notCalledWithMatch() {
2304 return !this.calledWithMatch
.apply(this, arguments
);
2307 returned
: function returned(value
) {
2308 return sinon
.deepEqual(value
, this.returnValue
);
2311 threw
: function threw(error
) {
2312 if (typeof error
=== "undefined" || !this.exception
) {
2313 return !!this.exception
;
2316 return this.exception
=== error
|| this.exception
.name
=== error
;
2319 calledWithNew
: function calledWithNew() {
2320 return this.proxy
.prototype && this.thisValue
instanceof this.proxy
;
2323 calledBefore: function (other
) {
2324 return this.callId
< other
.callId
;
2327 calledAfter: function (other
) {
2328 return this.callId
> other
.callId
;
2331 callArg: function (pos
) {
2335 callArgOn: function (pos
, thisValue
) {
2336 this.args
[pos
].apply(thisValue
);
2339 callArgWith: function (pos
) {
2340 this.callArgOnWith
.apply(this, [pos
, null].concat(slice
.call(arguments
, 1)));
2343 callArgOnWith: function (pos
, thisValue
) {
2344 var args
= slice
.call(arguments
, 2);
2345 this.args
[pos
].apply(thisValue
, args
);
2348 "yield": function () {
2349 this.yieldOn
.apply(this, [null].concat(slice
.call(arguments
, 0)));
2352 yieldOn: function (thisValue
) {
2353 var args
= this.args
;
2354 for (var i
= 0, l
= args
.length
; i
< l
; ++i
) {
2355 if (typeof args
[i
] === "function") {
2356 args
[i
].apply(thisValue
, slice
.call(arguments
, 1));
2360 throwYieldError(this.proxy
, " cannot yield since no callback was passed.", args
);
2363 yieldTo: function (prop
) {
2364 this.yieldToOn
.apply(this, [prop
, null].concat(slice
.call(arguments
, 1)));
2367 yieldToOn: function (prop
, thisValue
) {
2368 var args
= this.args
;
2369 for (var i
= 0, l
= args
.length
; i
< l
; ++i
) {
2370 if (args
[i
] && typeof args
[i
][prop
] === "function") {
2371 args
[i
][prop
].apply(thisValue
, slice
.call(arguments
, 2));
2375 throwYieldError(this.proxy
, " cannot yield to '" + prop
+
2376 "' since no callback was passed.", args
);
2379 getStackFrames: function () {
2380 // Omit the error message and the two top stack frames in sinon itself:
2381 return this.stack
&& this.stack
.split("\n").slice(3);
2384 toString: function () {
2385 var callStr
= this.proxy
? this.proxy
.toString() + "(" : "";
2392 for (var i
= 0, l
= this.args
.length
; i
< l
; ++i
) {
2393 args
.push(sinon
.format(this.args
[i
]));
2396 callStr
= callStr
+ args
.join(", ") + ")";
2398 if (typeof this.returnValue
!== "undefined") {
2399 callStr
+= " => " + sinon
.format(this.returnValue
);
2402 if (this.exception
) {
2403 callStr
+= " !" + this.exception
.name
;
2405 if (this.exception
.message
) {
2406 callStr
+= "(" + this.exception
.message
+ ")";
2410 callStr
+= this.getStackFrames()[0].replace(/^\s*(?:at\s+|@)?/, " at ");
2418 callProto
.invokeCallback
= callProto
.yield;
2420 function createSpyCall(spy
, thisValue
, args
, returnValue
, exception
, id
, stack
) {
2421 if (typeof id
!== "number") {
2422 throw new TypeError("Call id is not a number");
2424 var proxyCall
= sinon
.create(callProto
);
2425 proxyCall
.proxy
= spy
;
2426 proxyCall
.thisValue
= thisValue
;
2427 proxyCall
.args
= args
;
2428 proxyCall
.returnValue
= returnValue
;
2429 proxyCall
.exception
= exception
;
2430 proxyCall
.callId
= id
;
2431 proxyCall
.stack
= stack
;
2435 createSpyCall
.toString
= callProto
.toString
; // used by mocks
2437 sinon
.spyCall
= createSpyCall
;
2438 return createSpyCall
;
2441 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
2442 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
2444 function loadDependencies(require
, exports
, module
) {
2445 var sinon
= require("./util/core");
2447 require("./format");
2448 module
.exports
= makeApi(sinon
);
2452 define(loadDependencies
);
2457 loadDependencies(require
, module
.exports
, module
);
2462 makeApi(sinonGlobal
);
2465 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
2469 * @depend times_in_words.js
2470 * @depend util/core.js
2478 * @author Christian Johansen (christian@cjohansen.no)
2481 * Copyright (c) 2010-2013 Christian Johansen
2483 (function (sinonGlobal
) {
2485 function makeApi(sinon
) {
2486 var push
= Array
.prototype.push
;
2487 var slice
= Array
.prototype.slice
;
2490 function spy(object
, property
, types
) {
2491 if (!property
&& typeof object
=== "function") {
2492 return spy
.create(object
);
2495 if (!object
&& !property
) {
2496 return spy
.create(function () { });
2500 var methodDesc
= sinon
.getPropertyDescriptor(object
, property
);
2501 for (var i
= 0; i
< types
.length
; i
++) {
2502 methodDesc
[types
[i
]] = spy
.create(methodDesc
[types
[i
]]);
2504 return sinon
.wrapMethod(object
, property
, methodDesc
);
2507 return sinon
.wrapMethod(object
, property
, spy
.create(object
[property
]));
2510 function matchingFake(fakes
, args
, strict
) {
2515 for (var i
= 0, l
= fakes
.length
; i
< l
; i
++) {
2516 if (fakes
[i
].matches(args
, strict
)) {
2522 function incrementCallCount() {
2524 this.callCount
+= 1;
2525 this.notCalled
= false;
2526 this.calledOnce
= this.callCount
=== 1;
2527 this.calledTwice
= this.callCount
=== 2;
2528 this.calledThrice
= this.callCount
=== 3;
2531 function createCallProperties() {
2532 this.firstCall
= this.getCall(0);
2533 this.secondCall
= this.getCall(1);
2534 this.thirdCall
= this.getCall(2);
2535 this.lastCall
= this.getCall(this.callCount
- 1);
2538 var vars
= "a,b,c,d,e,f,g,h,i,j,k,l";
2539 function createProxy(func
, proxyLength
) {
2540 // Retain the function length:
2543 eval("p = (function proxy(" + vars
.substring(0, proxyLength
* 2 - 1) + // eslint-disable-line no-eval
2544 ") { return p.invoke(func, this, slice.call(arguments)); });");
2546 p
= function proxy() {
2547 return p
.invoke(func
, this, slice
.call(arguments
));
2550 p
.isSinonProxy
= true;
2558 reset: function () {
2559 if (this.invoking
) {
2560 var err
= new Error("Cannot reset Sinon function while invoking it. " +
2561 "Move the call to .reset outside of the callback.");
2562 err
.name
= "InvalidResetException";
2566 this.called
= false;
2567 this.notCalled
= true;
2568 this.calledOnce
= false;
2569 this.calledTwice
= false;
2570 this.calledThrice
= false;
2572 this.firstCall
= null;
2573 this.secondCall
= null;
2574 this.thirdCall
= null;
2575 this.lastCall
= null;
2577 this.returnValues
= [];
2578 this.thisValues
= [];
2579 this.exceptions
= [];
2583 for (var i
= 0; i
< this.fakes
.length
; i
++) {
2584 this.fakes
[i
].reset();
2591 create
: function create(func
, spyLength
) {
2594 if (typeof func
!== "function") {
2595 func = function () { };
2597 name
= sinon
.functionName(func
);
2601 spyLength
= func
.length
;
2604 var proxy
= createProxy(func
, spyLength
);
2606 sinon
.extend(proxy
, spy
);
2607 delete proxy
.create
;
2608 sinon
.extend(proxy
, func
);
2611 proxy
.prototype = func
.prototype;
2612 proxy
.displayName
= name
|| "spy";
2613 proxy
.toString
= sinon
.functionToString
;
2614 proxy
.instantiateFake
= sinon
.spy
.create
;
2615 proxy
.id
= "spy#" + uuid
++;
2620 invoke
: function invoke(func
, thisValue
, args
) {
2621 var matching
= matchingFake(this.fakes
, args
);
2622 var exception
, returnValue
;
2624 incrementCallCount
.call(this);
2625 push
.call(this.thisValues
, thisValue
);
2626 push
.call(this.args
, args
);
2627 push
.call(this.callIds
, callId
++);
2629 // Make call properties available from within the spied function:
2630 createCallProperties
.call(this);
2633 this.invoking
= true;
2636 returnValue
= matching
.invoke(func
, thisValue
, args
);
2638 returnValue
= (this.func
|| func
).apply(thisValue
, args
);
2641 var thisCall
= this.getCall(this.callCount
- 1);
2642 if (thisCall
.calledWithNew() && typeof returnValue
!== "object") {
2643 returnValue
= thisValue
;
2648 delete this.invoking
;
2651 push
.call(this.exceptions
, exception
);
2652 push
.call(this.returnValues
, returnValue
);
2653 push
.call(this.stacks
, new Error().stack
);
2655 // Make return value and exception available in the calls:
2656 createCallProperties
.call(this);
2658 if (exception
!== undefined) {
2665 named
: function named(name
) {
2666 this.displayName
= name
;
2670 getCall
: function getCall(i
) {
2671 if (i
< 0 || i
>= this.callCount
) {
2675 return sinon
.spyCall(this, this.thisValues
[i
], this.args
[i
],
2676 this.returnValues
[i
], this.exceptions
[i
],
2677 this.callIds
[i
], this.stacks
[i
]);
2680 getCalls: function () {
2684 for (i
= 0; i
< this.callCount
; i
++) {
2685 calls
.push(this.getCall(i
));
2691 calledBefore
: function calledBefore(spyFn
) {
2696 if (!spyFn
.called
) {
2700 return this.callIds
[0] < spyFn
.callIds
[spyFn
.callIds
.length
- 1];
2703 calledAfter
: function calledAfter(spyFn
) {
2704 if (!this.called
|| !spyFn
.called
) {
2708 return this.callIds
[this.callCount
- 1] > spyFn
.callIds
[spyFn
.callCount
- 1];
2711 withArgs: function () {
2712 var args
= slice
.call(arguments
);
2715 var match
= matchingFake(this.fakes
, args
, true);
2724 var original
= this;
2725 var fake
= this.instantiateFake();
2726 fake
.matchingAguments
= args
;
2728 push
.call(this.fakes
, fake
);
2730 fake
.withArgs = function () {
2731 return original
.withArgs
.apply(original
, arguments
);
2734 for (var i
= 0; i
< this.args
.length
; i
++) {
2735 if (fake
.matches(this.args
[i
])) {
2736 incrementCallCount
.call(fake
);
2737 push
.call(fake
.thisValues
, this.thisValues
[i
]);
2738 push
.call(fake
.args
, this.args
[i
]);
2739 push
.call(fake
.returnValues
, this.returnValues
[i
]);
2740 push
.call(fake
.exceptions
, this.exceptions
[i
]);
2741 push
.call(fake
.callIds
, this.callIds
[i
]);
2744 createCallProperties
.call(fake
);
2749 matches: function (args
, strict
) {
2750 var margs
= this.matchingAguments
;
2752 if (margs
.length
<= args
.length
&&
2753 sinon
.deepEqual(margs
, args
.slice(0, margs
.length
))) {
2754 return !strict
|| margs
.length
=== args
.length
;
2758 printf: function (format
) {
2759 var spyInstance
= this;
2760 var args
= slice
.call(arguments
, 1);
2763 return (format
|| "").replace(/%(.)/g, function (match
, specifyer
) {
2764 formatter
= spyApi
.formatters
[specifyer
];
2766 if (typeof formatter
=== "function") {
2767 return formatter
.call(null, spyInstance
, args
);
2768 } else if (!isNaN(parseInt(specifyer
, 10))) {
2769 return sinon
.format(args
[specifyer
- 1]);
2772 return "%" + specifyer
;
2777 function delegateToCalls(method
, matchAny
, actual
, notCalled
) {
2778 spyApi
[method
] = function () {
2781 return notCalled
.apply(this, arguments
);
2789 for (var i
= 0, l
= this.callCount
; i
< l
; i
+= 1) {
2790 currentCall
= this.getCall(i
);
2792 if (currentCall
[actual
|| method
].apply(currentCall
, arguments
)) {
2801 return matches
=== this.callCount
;
2805 delegateToCalls("calledOn", true);
2806 delegateToCalls("alwaysCalledOn", false, "calledOn");
2807 delegateToCalls("calledWith", true);
2808 delegateToCalls("calledWithMatch", true);
2809 delegateToCalls("alwaysCalledWith", false, "calledWith");
2810 delegateToCalls("alwaysCalledWithMatch", false, "calledWithMatch");
2811 delegateToCalls("calledWithExactly", true);
2812 delegateToCalls("alwaysCalledWithExactly", false, "calledWithExactly");
2813 delegateToCalls("neverCalledWith", false, "notCalledWith", function () {
2816 delegateToCalls("neverCalledWithMatch", false, "notCalledWithMatch", function () {
2819 delegateToCalls("threw", true);
2820 delegateToCalls("alwaysThrew", false, "threw");
2821 delegateToCalls("returned", true);
2822 delegateToCalls("alwaysReturned", false, "returned");
2823 delegateToCalls("calledWithNew", true);
2824 delegateToCalls("alwaysCalledWithNew", false, "calledWithNew");
2825 delegateToCalls("callArg", false, "callArgWith", function () {
2826 throw new Error(this.toString() + " cannot call arg since it was not yet invoked.");
2828 spyApi
.callArgWith
= spyApi
.callArg
;
2829 delegateToCalls("callArgOn", false, "callArgOnWith", function () {
2830 throw new Error(this.toString() + " cannot call arg since it was not yet invoked.");
2832 spyApi
.callArgOnWith
= spyApi
.callArgOn
;
2833 delegateToCalls("yield", false, "yield", function () {
2834 throw new Error(this.toString() + " cannot yield since it was not yet invoked.");
2836 // "invokeCallback" is an alias for "yield" since "yield" is invalid in strict mode.
2837 spyApi
.invokeCallback
= spyApi
.yield;
2838 delegateToCalls("yieldOn", false, "yieldOn", function () {
2839 throw new Error(this.toString() + " cannot yield since it was not yet invoked.");
2841 delegateToCalls("yieldTo", false, "yieldTo", function (property
) {
2842 throw new Error(this.toString() + " cannot yield to '" + property
+
2843 "' since it was not yet invoked.");
2845 delegateToCalls("yieldToOn", false, "yieldToOn", function (property
) {
2846 throw new Error(this.toString() + " cannot yield to '" + property
+
2847 "' since it was not yet invoked.");
2850 spyApi
.formatters
= {
2851 c: function (spyInstance
) {
2852 return sinon
.timesInWords(spyInstance
.callCount
);
2855 n: function (spyInstance
) {
2856 return spyInstance
.toString();
2859 C: function (spyInstance
) {
2862 for (var i
= 0, l
= spyInstance
.callCount
; i
< l
; ++i
) {
2863 var stringifiedCall
= " " + spyInstance
.getCall(i
).toString();
2864 if (/\n/.test(calls
[i
- 1])) {
2865 stringifiedCall
= "\n" + stringifiedCall
;
2867 push
.call(calls
, stringifiedCall
);
2870 return calls
.length
> 0 ? "\n" + calls
.join("\n") : "";
2873 t: function (spyInstance
) {
2876 for (var i
= 0, l
= spyInstance
.callCount
; i
< l
; ++i
) {
2877 push
.call(objects
, sinon
.format(spyInstance
.thisValues
[i
]));
2880 return objects
.join(", ");
2883 "*": function (spyInstance
, args
) {
2886 for (var i
= 0, l
= args
.length
; i
< l
; ++i
) {
2887 push
.call(formatted
, sinon
.format(args
[i
]));
2890 return formatted
.join(", ");
2894 sinon
.extend(spy
, spyApi
);
2896 spy
.spyCall
= sinon
.spyCall
;
2902 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
2903 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
2905 function loadDependencies(require
, exports
, module
) {
2906 var core
= require("./util/core");
2908 require("./extend");
2909 require("./times_in_words");
2910 require("./format");
2911 module
.exports
= makeApi(core
);
2915 define(loadDependencies
);
2920 loadDependencies(require
, module
.exports
, module
);
2925 makeApi(sinonGlobal
);
2928 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
2932 * @depend util/core.js
2938 * @author Christian Johansen (christian@cjohansen.no)
2939 * @author Tim Fischbach (mail@timfischbach.de)
2942 * Copyright (c) 2010-2013 Christian Johansen
2944 (function (sinonGlobal
) {
2946 var slice
= Array
.prototype.slice
;
2947 var join
= Array
.prototype.join
;
2948 var useLeftMostCallback
= -1;
2949 var useRightMostCallback
= -2;
2951 var nextTick
= (function () {
2952 if (typeof process
=== "object" && typeof process
.nextTick
=== "function") {
2953 return process
.nextTick
;
2956 if (typeof setImmediate
=== "function") {
2957 return setImmediate
;
2960 return function (callback
) {
2961 setTimeout(callback
, 0);
2965 function throwsException(error
, message
) {
2966 if (typeof error
=== "string") {
2967 this.exception
= new Error(message
|| "");
2968 this.exception
.name
= error
;
2969 } else if (!error
) {
2970 this.exception
= new Error("Error");
2972 this.exception
= error
;
2978 function getCallback(behavior
, args
) {
2979 var callArgAt
= behavior
.callArgAt
;
2981 if (callArgAt
>= 0) {
2982 return args
[callArgAt
];
2987 if (callArgAt
=== useLeftMostCallback
) {
2988 argumentList
= args
;
2991 if (callArgAt
=== useRightMostCallback
) {
2992 argumentList
= slice
.call(args
).reverse();
2995 var callArgProp
= behavior
.callArgProp
;
2997 for (var i
= 0, l
= argumentList
.length
; i
< l
; ++i
) {
2998 if (!callArgProp
&& typeof argumentList
[i
] === "function") {
2999 return argumentList
[i
];
3002 if (callArgProp
&& argumentList
[i
] &&
3003 typeof argumentList
[i
][callArgProp
] === "function") {
3004 return argumentList
[i
][callArgProp
];
3011 function makeApi(sinon
) {
3012 function getCallbackError(behavior
, func
, args
) {
3013 if (behavior
.callArgAt
< 0) {
3016 if (behavior
.callArgProp
) {
3017 msg
= sinon
.functionName(behavior
.stub
) +
3018 " expected to yield to '" + behavior
.callArgProp
+
3019 "', but no object with such a property was passed.";
3021 msg
= sinon
.functionName(behavior
.stub
) +
3022 " expected to yield, but no callback was passed.";
3025 if (args
.length
> 0) {
3026 msg
+= " Received [" + join
.call(args
, ", ") + "]";
3032 return "argument at index " + behavior
.callArgAt
+ " is not a function: " + func
;
3035 function callCallback(behavior
, args
) {
3036 if (typeof behavior
.callArgAt
=== "number") {
3037 var func
= getCallback(behavior
, args
);
3039 if (typeof func
!== "function") {
3040 throw new TypeError(getCallbackError(behavior
, func
, args
));
3043 if (behavior
.callbackAsync
) {
3044 nextTick(function () {
3045 func
.apply(behavior
.callbackContext
, behavior
.callbackArguments
);
3048 func
.apply(behavior
.callbackContext
, behavior
.callbackArguments
);
3054 create
: function create(stub
) {
3055 var behavior
= sinon
.extend({}, sinon
.behavior
);
3056 delete behavior
.create
;
3057 behavior
.stub
= stub
;
3062 isPresent
: function isPresent() {
3063 return (typeof this.callArgAt
=== "number" ||
3065 typeof this.returnArgAt
=== "number" ||
3067 this.returnValueDefined
);
3070 invoke
: function invoke(context
, args
) {
3071 callCallback(this, args
);
3073 if (this.exception
) {
3074 throw this.exception
;
3075 } else if (typeof this.returnArgAt
=== "number") {
3076 return args
[this.returnArgAt
];
3077 } else if (this.returnThis
) {
3081 return this.returnValue
;
3084 onCall
: function onCall(index
) {
3085 return this.stub
.onCall(index
);
3088 onFirstCall
: function onFirstCall() {
3089 return this.stub
.onFirstCall();
3092 onSecondCall
: function onSecondCall() {
3093 return this.stub
.onSecondCall();
3096 onThirdCall
: function onThirdCall() {
3097 return this.stub
.onThirdCall();
3100 withArgs
: function withArgs(/* arguments */) {
3102 "Defining a stub by invoking \"stub.onCall(...).withArgs(...)\" " +
3103 "is not supported. Use \"stub.withArgs(...).onCall(...)\" " +
3104 "to define sequential behavior for calls with certain arguments."
3108 callsArg
: function callsArg(pos
) {
3109 if (typeof pos
!== "number") {
3110 throw new TypeError("argument index is not number");
3113 this.callArgAt
= pos
;
3114 this.callbackArguments
= [];
3115 this.callbackContext
= undefined;
3116 this.callArgProp
= undefined;
3117 this.callbackAsync
= false;
3122 callsArgOn
: function callsArgOn(pos
, context
) {
3123 if (typeof pos
!== "number") {
3124 throw new TypeError("argument index is not number");
3126 if (typeof context
!== "object") {
3127 throw new TypeError("argument context is not an object");
3130 this.callArgAt
= pos
;
3131 this.callbackArguments
= [];
3132 this.callbackContext
= context
;
3133 this.callArgProp
= undefined;
3134 this.callbackAsync
= false;
3139 callsArgWith
: function callsArgWith(pos
) {
3140 if (typeof pos
!== "number") {
3141 throw new TypeError("argument index is not number");
3144 this.callArgAt
= pos
;
3145 this.callbackArguments
= slice
.call(arguments
, 1);
3146 this.callbackContext
= undefined;
3147 this.callArgProp
= undefined;
3148 this.callbackAsync
= false;
3153 callsArgOnWith
: function callsArgWith(pos
, context
) {
3154 if (typeof pos
!== "number") {
3155 throw new TypeError("argument index is not number");
3157 if (typeof context
!== "object") {
3158 throw new TypeError("argument context is not an object");
3161 this.callArgAt
= pos
;
3162 this.callbackArguments
= slice
.call(arguments
, 2);
3163 this.callbackContext
= context
;
3164 this.callArgProp
= undefined;
3165 this.callbackAsync
= false;
3170 yields: function () {
3171 this.callArgAt
= useLeftMostCallback
;
3172 this.callbackArguments
= slice
.call(arguments
, 0);
3173 this.callbackContext
= undefined;
3174 this.callArgProp
= undefined;
3175 this.callbackAsync
= false;
3180 yieldsRight: function () {
3181 this.callArgAt
= useRightMostCallback
;
3182 this.callbackArguments
= slice
.call(arguments
, 0);
3183 this.callbackContext
= undefined;
3184 this.callArgProp
= undefined;
3185 this.callbackAsync
= false;
3190 yieldsOn: function (context
) {
3191 if (typeof context
!== "object") {
3192 throw new TypeError("argument context is not an object");
3195 this.callArgAt
= useLeftMostCallback
;
3196 this.callbackArguments
= slice
.call(arguments
, 1);
3197 this.callbackContext
= context
;
3198 this.callArgProp
= undefined;
3199 this.callbackAsync
= false;
3204 yieldsTo: function (prop
) {
3205 this.callArgAt
= useLeftMostCallback
;
3206 this.callbackArguments
= slice
.call(arguments
, 1);
3207 this.callbackContext
= undefined;
3208 this.callArgProp
= prop
;
3209 this.callbackAsync
= false;
3214 yieldsToOn: function (prop
, context
) {
3215 if (typeof context
!== "object") {
3216 throw new TypeError("argument context is not an object");
3219 this.callArgAt
= useLeftMostCallback
;
3220 this.callbackArguments
= slice
.call(arguments
, 2);
3221 this.callbackContext
= context
;
3222 this.callArgProp
= prop
;
3223 this.callbackAsync
= false;
3228 throws: throwsException
,
3229 throwsException
: throwsException
,
3231 returns
: function returns(value
) {
3232 this.returnValue
= value
;
3233 this.returnValueDefined
= true;
3234 this.exception
= undefined;
3239 returnsArg
: function returnsArg(pos
) {
3240 if (typeof pos
!== "number") {
3241 throw new TypeError("argument index is not number");
3244 this.returnArgAt
= pos
;
3249 returnsThis
: function returnsThis() {
3250 this.returnThis
= true;
3256 function createAsyncVersion(syncFnName
) {
3257 return function () {
3258 var result
= this[syncFnName
].apply(this, arguments
);
3259 this.callbackAsync
= true;
3264 // create asynchronous versions of callsArg* and yields* methods
3265 for (var method
in proto
) {
3266 // need to avoid creating anotherasync versions of the newly added async methods
3267 if (proto
.hasOwnProperty(method
) && method
.match(/^(callsArg|yields)/) && !method
.match(/Async/)) {
3268 proto
[method
+ "Async"] = createAsyncVersion(method
);
3272 sinon
.behavior
= proto
;
3276 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
3277 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
3279 function loadDependencies(require
, exports
, module
) {
3280 var sinon
= require("./util/core");
3281 require("./extend");
3282 module
.exports
= makeApi(sinon
);
3286 define(loadDependencies
);
3291 loadDependencies(require
, module
.exports
, module
);
3296 makeApi(sinonGlobal
);
3299 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
3303 * @depend util/core.js
3305 (function (sinonGlobal
) {
3307 function makeApi(sinon
) {
3308 function walkInternal(obj
, iterator
, context
, originalObj
, seen
) {
3311 if (typeof Object
.getOwnPropertyNames
!== "function") {
3312 // We explicitly want to enumerate through all of the prototype's properties
3313 // in this case, therefore we deliberately leave out an own property check.
3314 /* eslint-disable guard-for-in */
3316 iterator
.call(context
, obj
[prop
], prop
, obj
);
3318 /* eslint-enable guard-for-in */
3323 Object
.getOwnPropertyNames(obj
).forEach(function (k
) {
3326 var target
= typeof Object
.getOwnPropertyDescriptor(obj
, k
).get === "function" ?
3328 iterator
.call(context
, target
[k
], k
, target
);
3332 proto
= Object
.getPrototypeOf(obj
);
3334 walkInternal(proto
, iterator
, context
, originalObj
, seen
);
3338 /* Public: walks the prototype chain of an object and iterates over every own property
3339 * name encountered. The iterator is called in the same fashion that Array.prototype.forEach
3340 * works, where it is passed the value, key, and own object as the 1st, 2nd, and 3rd positional
3341 * argument, respectively. In cases where Object.getOwnPropertyNames is not available, walk will
3342 * default to using a simple for..in loop.
3344 * obj - The object to walk the prototype chain for.
3345 * iterator - The function to be called on each pass of the walk.
3346 * context - (Optional) When given, the iterator will be called with this object as the receiver.
3348 function walk(obj
, iterator
, context
) {
3349 return walkInternal(obj
, iterator
, context
, obj
, {});
3356 function loadDependencies(require
, exports
, module
) {
3357 var sinon
= require("./util/core");
3358 module
.exports
= makeApi(sinon
);
3361 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
3362 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
3365 define(loadDependencies
);
3370 loadDependencies(require
, module
.exports
, module
);
3375 makeApi(sinonGlobal
);
3378 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
3382 * @depend util/core.js
3385 * @depend behavior.js
3391 * @author Christian Johansen (christian@cjohansen.no)
3394 * Copyright (c) 2010-2013 Christian Johansen
3396 (function (sinonGlobal
) {
3398 function makeApi(sinon
) {
3399 function stub(object
, property
, func
) {
3400 if (!!func
&& typeof func
!== "function" && typeof func
!== "object") {
3401 throw new TypeError("Custom stub should be a function or a property descriptor");
3407 if (typeof func
=== "function") {
3408 wrapper
= sinon
.spy
&& sinon
.spy
.create
? sinon
.spy
.create(func
) : func
;
3411 if (sinon
.spy
&& sinon
.spy
.create
) {
3412 var types
= sinon
.objectKeys(wrapper
);
3413 for (var i
= 0; i
< types
.length
; i
++) {
3414 wrapper
[types
[i
]] = sinon
.spy
.create(wrapper
[types
[i
]]);
3420 if (typeof object
=== "object" && typeof object
[property
] === "function") {
3421 stubLength
= object
[property
].length
;
3423 wrapper
= stub
.create(stubLength
);
3426 if (!object
&& typeof property
=== "undefined") {
3427 return sinon
.stub
.create();
3430 if (typeof property
=== "undefined" && typeof object
=== "object") {
3431 sinon
.walk(object
|| {}, function (value
, prop
, propOwner
) {
3432 // we don't want to stub things like toString(), valueOf(), etc. so we only stub if the object
3433 // is not Object.prototype
3435 propOwner
!== Object
.prototype &&
3436 prop
!== "constructor" &&
3437 typeof sinon
.getPropertyDescriptor(propOwner
, prop
).value
=== "function"
3446 return sinon
.wrapMethod(object
, property
, wrapper
);
3450 /*eslint-disable no-use-before-define*/
3451 function getParentBehaviour(stubInstance
) {
3452 return (stubInstance
.parent
&& getCurrentBehavior(stubInstance
.parent
));
3455 function getDefaultBehavior(stubInstance
) {
3456 return stubInstance
.defaultBehavior
||
3457 getParentBehaviour(stubInstance
) ||
3458 sinon
.behavior
.create(stubInstance
);
3461 function getCurrentBehavior(stubInstance
) {
3462 var behavior
= stubInstance
.behaviors
[stubInstance
.callCount
- 1];
3463 return behavior
&& behavior
.isPresent() ? behavior
: getDefaultBehavior(stubInstance
);
3465 /*eslint-enable no-use-before-define*/
3470 create
: function create(stubLength
) {
3471 var functionStub = function () {
3472 return getCurrentBehavior(functionStub
).invoke(this, arguments
);
3475 functionStub
.id
= "stub#" + uuid
++;
3476 var orig
= functionStub
;
3477 functionStub
= sinon
.spy
.create(functionStub
, stubLength
);
3478 functionStub
.func
= orig
;
3480 sinon
.extend(functionStub
, stub
);
3481 functionStub
.instantiateFake
= sinon
.stub
.create
;
3482 functionStub
.displayName
= "stub";
3483 functionStub
.toString
= sinon
.functionToString
;
3485 functionStub
.defaultBehavior
= null;
3486 functionStub
.behaviors
= [];
3488 return functionStub
;
3491 resetBehavior: function () {
3494 this.defaultBehavior
= null;
3495 this.behaviors
= [];
3497 delete this.returnValue
;
3498 delete this.returnArgAt
;
3499 this.returnThis
= false;
3502 for (i
= 0; i
< this.fakes
.length
; i
++) {
3503 this.fakes
[i
].resetBehavior();
3508 onCall
: function onCall(index
) {
3509 if (!this.behaviors
[index
]) {
3510 this.behaviors
[index
] = sinon
.behavior
.create(this);
3513 return this.behaviors
[index
];
3516 onFirstCall
: function onFirstCall() {
3517 return this.onCall(0);
3520 onSecondCall
: function onSecondCall() {
3521 return this.onCall(1);
3524 onThirdCall
: function onThirdCall() {
3525 return this.onCall(2);
3529 function createBehavior(behaviorMethod
) {
3530 return function () {
3531 this.defaultBehavior
= this.defaultBehavior
|| sinon
.behavior
.create(this);
3532 this.defaultBehavior
[behaviorMethod
].apply(this.defaultBehavior
, arguments
);
3537 for (var method
in sinon
.behavior
) {
3538 if (sinon
.behavior
.hasOwnProperty(method
) &&
3539 !proto
.hasOwnProperty(method
) &&
3540 method
!== "create" &&
3541 method
!== "withArgs" &&
3542 method
!== "invoke") {
3543 proto
[method
] = createBehavior(method
);
3547 sinon
.extend(stub
, proto
);
3553 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
3554 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
3556 function loadDependencies(require
, exports
, module
) {
3557 var core
= require("./util/core");
3558 require("./behavior");
3560 require("./extend");
3561 module
.exports
= makeApi(core
);
3565 define(loadDependencies
);
3570 loadDependencies(require
, module
.exports
, module
);
3575 makeApi(sinonGlobal
);
3578 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
3582 * @depend times_in_words.js
3583 * @depend util/core.js
3594 * @author Christian Johansen (christian@cjohansen.no)
3597 * Copyright (c) 2010-2013 Christian Johansen
3599 (function (sinonGlobal
) {
3601 function makeApi(sinon
) {
3603 var match
= sinon
.match
;
3605 function mock(object
) {
3606 // if (typeof console !== undefined && console.warn) {
3607 // console.warn("mock will be removed from Sinon.JS v2.0");
3611 return sinon
.expectation
.create("Anonymous mock");
3614 return mock
.create(object
);
3617 function each(collection
, callback
) {
3622 for (var i
= 0, l
= collection
.length
; i
< l
; i
+= 1) {
3623 callback(collection
[i
]);
3627 function arrayEquals(arr1
, arr2
, compareLength
) {
3628 if (compareLength
&& (arr1
.length
!== arr2
.length
)) {
3632 for (var i
= 0, l
= arr1
.length
; i
< l
; i
++) {
3633 if (!sinon
.deepEqual(arr1
[i
], arr2
[i
])) {
3640 sinon
.extend(mock
, {
3641 create
: function create(object
) {
3643 throw new TypeError("object is null");
3646 var mockObject
= sinon
.extend({}, mock
);
3647 mockObject
.object
= object
;
3648 delete mockObject
.create
;
3653 expects
: function expects(method
) {
3655 throw new TypeError("method is falsy");
3658 if (!this.expectations
) {
3659 this.expectations
= {};
3663 if (!this.expectations
[method
]) {
3664 this.expectations
[method
] = [];
3665 var mockObject
= this;
3667 sinon
.wrapMethod(this.object
, method
, function () {
3668 return mockObject
.invokeMethod(method
, this, arguments
);
3671 push
.call(this.proxies
, method
);
3674 var expectation
= sinon
.expectation
.create(method
);
3675 push
.call(this.expectations
[method
], expectation
);
3680 restore
: function restore() {
3681 var object
= this.object
;
3683 each(this.proxies
, function (proxy
) {
3684 if (typeof object
[proxy
].restore
=== "function") {
3685 object
[proxy
].restore();
3690 verify
: function verify() {
3691 var expectations
= this.expectations
|| {};
3695 each(this.proxies
, function (proxy
) {
3696 each(expectations
[proxy
], function (expectation
) {
3697 if (!expectation
.met()) {
3698 push
.call(messages
, expectation
.toString());
3700 push
.call(met
, expectation
.toString());
3707 if (messages
.length
> 0) {
3708 sinon
.expectation
.fail(messages
.concat(met
).join("\n"));
3709 } else if (met
.length
> 0) {
3710 sinon
.expectation
.pass(messages
.concat(met
).join("\n"));
3716 invokeMethod
: function invokeMethod(method
, thisValue
, args
) {
3717 var expectations
= this.expectations
&& this.expectations
[method
] ? this.expectations
[method
] : [];
3718 var expectationsWithMatchingArgs
= [];
3719 var currentArgs
= args
|| [];
3722 for (i
= 0; i
< expectations
.length
; i
+= 1) {
3723 var expectedArgs
= expectations
[i
].expectedArguments
|| [];
3724 if (arrayEquals(expectedArgs
, currentArgs
, expectations
[i
].expectsExactArgCount
)) {
3725 expectationsWithMatchingArgs
.push(expectations
[i
]);
3729 for (i
= 0; i
< expectationsWithMatchingArgs
.length
; i
+= 1) {
3730 if (!expectationsWithMatchingArgs
[i
].met() &&
3731 expectationsWithMatchingArgs
[i
].allowsCall(thisValue
, args
)) {
3732 return expectationsWithMatchingArgs
[i
].apply(thisValue
, args
);
3739 for (i
= 0; i
< expectationsWithMatchingArgs
.length
; i
+= 1) {
3740 if (expectationsWithMatchingArgs
[i
].allowsCall(thisValue
, args
)) {
3741 available
= available
|| expectationsWithMatchingArgs
[i
];
3747 if (available
&& exhausted
=== 0) {
3748 return available
.apply(thisValue
, args
);
3751 for (i
= 0; i
< expectations
.length
; i
+= 1) {
3752 push
.call(messages
, " " + expectations
[i
].toString());
3755 messages
.unshift("Unexpected call: " + sinon
.spyCall
.toString
.call({
3760 sinon
.expectation
.fail(messages
.join("\n"));
3764 var times
= sinon
.timesInWords
;
3765 var slice
= Array
.prototype.slice
;
3767 function callCountInWords(callCount
) {
3768 if (callCount
=== 0) {
3769 return "never called";
3772 return "called " + times(callCount
);
3775 function expectedCallCountInWords(expectation
) {
3776 var min
= expectation
.minCalls
;
3777 var max
= expectation
.maxCalls
;
3779 if (typeof min
=== "number" && typeof max
=== "number") {
3780 var str
= times(min
);
3783 str
= "at least " + str
+ " and at most " + times(max
);
3789 if (typeof min
=== "number") {
3790 return "at least " + times(min
);
3793 return "at most " + times(max
);
3796 function receivedMinCalls(expectation
) {
3797 var hasMinLimit
= typeof expectation
.minCalls
=== "number";
3798 return !hasMinLimit
|| expectation
.callCount
>= expectation
.minCalls
;
3801 function receivedMaxCalls(expectation
) {
3802 if (typeof expectation
.maxCalls
!== "number") {
3806 return expectation
.callCount
=== expectation
.maxCalls
;
3809 function verifyMatcher(possibleMatcher
, arg
) {
3810 var isMatcher
= match
&& match
.isMatcher(possibleMatcher
);
3812 return isMatcher
&& possibleMatcher
.test(arg
) || true;
3815 sinon
.expectation
= {
3819 create
: function create(methodName
) {
3820 var expectation
= sinon
.extend(sinon
.stub
.create(), sinon
.expectation
);
3821 delete expectation
.create
;
3822 expectation
.method
= methodName
;
3827 invoke
: function invoke(func
, thisValue
, args
) {
3828 this.verifyCallAllowed(thisValue
, args
);
3830 return sinon
.spy
.invoke
.apply(this, arguments
);
3833 atLeast
: function atLeast(num
) {
3834 if (typeof num
!== "number") {
3835 throw new TypeError("'" + num
+ "' is not number");
3838 if (!this.limitsSet
) {
3839 this.maxCalls
= null;
3840 this.limitsSet
= true;
3843 this.minCalls
= num
;
3848 atMost
: function atMost(num
) {
3849 if (typeof num
!== "number") {
3850 throw new TypeError("'" + num
+ "' is not number");
3853 if (!this.limitsSet
) {
3854 this.minCalls
= null;
3855 this.limitsSet
= true;
3858 this.maxCalls
= num
;
3863 never
: function never() {
3864 return this.exactly(0);
3867 once
: function once() {
3868 return this.exactly(1);
3871 twice
: function twice() {
3872 return this.exactly(2);
3875 thrice
: function thrice() {
3876 return this.exactly(3);
3879 exactly
: function exactly(num
) {
3880 if (typeof num
!== "number") {
3881 throw new TypeError("'" + num
+ "' is not a number");
3885 return this.atMost(num
);
3888 met
: function met() {
3889 return !this.failed
&& receivedMinCalls(this);
3892 verifyCallAllowed
: function verifyCallAllowed(thisValue
, args
) {
3893 if (receivedMaxCalls(this)) {
3895 sinon
.expectation
.fail(this.method
+ " already called " + times(this.maxCalls
));
3898 if ("expectedThis" in this && this.expectedThis
!== thisValue
) {
3899 sinon
.expectation
.fail(this.method
+ " called with " + thisValue
+ " as thisValue, expected " +
3903 if (!("expectedArguments" in this)) {
3908 sinon
.expectation
.fail(this.method
+ " received no arguments, expected " +
3909 sinon
.format(this.expectedArguments
));
3912 if (args
.length
< this.expectedArguments
.length
) {
3913 sinon
.expectation
.fail(this.method
+ " received too few arguments (" + sinon
.format(args
) +
3914 "), expected " + sinon
.format(this.expectedArguments
));
3917 if (this.expectsExactArgCount
&&
3918 args
.length
!== this.expectedArguments
.length
) {
3919 sinon
.expectation
.fail(this.method
+ " received too many arguments (" + sinon
.format(args
) +
3920 "), expected " + sinon
.format(this.expectedArguments
));
3923 for (var i
= 0, l
= this.expectedArguments
.length
; i
< l
; i
+= 1) {
3925 if (!verifyMatcher(this.expectedArguments
[i
], args
[i
])) {
3926 sinon
.expectation
.fail(this.method
+ " received wrong arguments " + sinon
.format(args
) +
3927 ", didn't match " + this.expectedArguments
.toString());
3930 if (!sinon
.deepEqual(this.expectedArguments
[i
], args
[i
])) {
3931 sinon
.expectation
.fail(this.method
+ " received wrong arguments " + sinon
.format(args
) +
3932 ", expected " + sinon
.format(this.expectedArguments
));
3937 allowsCall
: function allowsCall(thisValue
, args
) {
3938 if (this.met() && receivedMaxCalls(this)) {
3942 if ("expectedThis" in this && this.expectedThis
!== thisValue
) {
3946 if (!("expectedArguments" in this)) {
3952 if (args
.length
< this.expectedArguments
.length
) {
3956 if (this.expectsExactArgCount
&&
3957 args
.length
!== this.expectedArguments
.length
) {
3961 for (var i
= 0, l
= this.expectedArguments
.length
; i
< l
; i
+= 1) {
3962 if (!verifyMatcher(this.expectedArguments
[i
], args
[i
])) {
3966 if (!sinon
.deepEqual(this.expectedArguments
[i
], args
[i
])) {
3974 withArgs
: function withArgs() {
3975 this.expectedArguments
= slice
.call(arguments
);
3979 withExactArgs
: function withExactArgs() {
3980 this.withArgs
.apply(this, arguments
);
3981 this.expectsExactArgCount
= true;
3985 on
: function on(thisValue
) {
3986 this.expectedThis
= thisValue
;
3990 toString: function () {
3991 var args
= (this.expectedArguments
|| []).slice();
3993 if (!this.expectsExactArgCount
) {
3994 push
.call(args
, "[...]");
3997 var callStr
= sinon
.spyCall
.toString
.call({
3998 proxy
: this.method
|| "anonymous mock expectation",
4002 var message
= callStr
.replace(", [...", "[, ...") + " " +
4003 expectedCallCountInWords(this);
4006 return "Expectation met: " + message
;
4009 return "Expected " + message
+ " (" +
4010 callCountInWords(this.callCount
) + ")";
4013 verify
: function verify() {
4015 sinon
.expectation
.fail(this.toString());
4017 sinon
.expectation
.pass(this.toString());
4023 pass
: function pass(message
) {
4024 sinon
.assert
.pass(message
);
4027 fail
: function fail(message
) {
4028 var exception
= new Error(message
);
4029 exception
.name
= "ExpectationError";
4039 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
4040 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
4042 function loadDependencies(require
, exports
, module
) {
4043 var sinon
= require("./util/core");
4044 require("./times_in_words");
4046 require("./extend");
4050 require("./format");
4052 module
.exports
= makeApi(sinon
);
4056 define(loadDependencies
);
4061 loadDependencies(require
, module
.exports
, module
);
4066 makeApi(sinonGlobal
);
4069 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
4073 * @depend util/core.js
4079 * Collections of stubs, spies and mocks.
4081 * @author Christian Johansen (christian@cjohansen.no)
4084 * Copyright (c) 2010-2013 Christian Johansen
4086 (function (sinonGlobal
) {
4089 var hasOwnProperty
= Object
.prototype.hasOwnProperty
;
4091 function getFakes(fakeCollection
) {
4092 if (!fakeCollection
.fakes
) {
4093 fakeCollection
.fakes
= [];
4096 return fakeCollection
.fakes
;
4099 function each(fakeCollection
, method
) {
4100 var fakes
= getFakes(fakeCollection
);
4102 for (var i
= 0, l
= fakes
.length
; i
< l
; i
+= 1) {
4103 if (typeof fakes
[i
][method
] === "function") {
4109 function compact(fakeCollection
) {
4110 var fakes
= getFakes(fakeCollection
);
4112 while (i
< fakes
.length
) {
4117 function makeApi(sinon
) {
4119 verify
: function resolve() {
4120 each(this, "verify");
4123 restore
: function restore() {
4124 each(this, "restore");
4128 reset
: function restore() {
4129 each(this, "reset");
4132 verifyAndRestore
: function verifyAndRestore() {
4148 add
: function add(fake
) {
4149 push
.call(getFakes(this), fake
);
4153 spy
: function spy() {
4154 return this.add(sinon
.spy
.apply(sinon
, arguments
));
4157 stub
: function stub(object
, property
, value
) {
4159 var original
= object
[property
];
4161 if (typeof original
!== "function") {
4162 if (!hasOwnProperty
.call(object
, property
)) {
4163 throw new TypeError("Cannot stub non-existent own property " + property
);
4166 object
[property
] = value
;
4169 restore: function () {
4170 object
[property
] = original
;
4175 if (!property
&& !!object
&& typeof object
=== "object") {
4176 var stubbedObj
= sinon
.stub
.apply(sinon
, arguments
);
4178 for (var prop
in stubbedObj
) {
4179 if (typeof stubbedObj
[prop
] === "function") {
4180 this.add(stubbedObj
[prop
]);
4187 return this.add(sinon
.stub
.apply(sinon
, arguments
));
4190 mock
: function mock() {
4191 return this.add(sinon
.mock
.apply(sinon
, arguments
));
4194 inject
: function inject(obj
) {
4197 obj
.spy = function () {
4198 return col
.spy
.apply(col
, arguments
);
4201 obj
.stub = function () {
4202 return col
.stub
.apply(col
, arguments
);
4205 obj
.mock = function () {
4206 return col
.mock
.apply(col
, arguments
);
4213 sinon
.collection
= collection
;
4217 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
4218 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
4220 function loadDependencies(require
, exports
, module
) {
4221 var sinon
= require("./util/core");
4225 module
.exports
= makeApi(sinon
);
4229 define(loadDependencies
);
4234 loadDependencies(require
, module
.exports
, module
);
4239 makeApi(sinonGlobal
);
4242 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
4255 * Inspired by jsUnitMockTimeOut from JsUnit
4257 * @author Christian Johansen (christian@cjohansen.no)
4260 * Copyright (c) 2010-2013 Christian Johansen
4264 function makeApi(s
, lol
) {
4266 var llx
= typeof lolex
!== "undefined" ? lolex
: lol
;
4268 s
.useFakeTimers = function () {
4270 var methods
= Array
.prototype.slice
.call(arguments
);
4272 if (typeof methods
[0] === "string") {
4275 now
= methods
.shift();
4278 var clock
= llx
.install(now
|| 0, methods
);
4279 clock
.restore
= clock
.uninstall
;
4284 create: function (now
) {
4285 return llx
.createClock(now
);
4290 setTimeout
: setTimeout
,
4291 clearTimeout
: clearTimeout
,
4292 setImmediate
: (typeof setImmediate
!== "undefined" ? setImmediate
: undefined),
4293 clearImmediate
: (typeof clearImmediate
!== "undefined" ? clearImmediate
: undefined),
4294 setInterval
: setInterval
,
4295 clearInterval
: clearInterval
,
4300 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
4301 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
4303 function loadDependencies(require
, epxorts
, module
, lolex
) {
4304 var core
= require("./core");
4305 makeApi(core
, lolex
);
4306 module
.exports
= core
;
4310 define(loadDependencies
);
4311 } else if (isNode
) {
4312 loadDependencies(require
, module
.exports
, module
, require("lolex"));
4314 makeApi(sinon
); // eslint-disable-line no-undef
4319 * Minimal Event interface implementation
4321 * Original implementation by Sven Fuchs: https://gist.github.com/995028
4322 * Modifications and tests by Christian Johansen.
4324 * @author Sven Fuchs (svenfuchs@artweb-design.de)
4325 * @author Christian Johansen (christian@cjohansen.no)
4328 * Copyright (c) 2011 Sven Fuchs, Christian Johansen
4330 if (typeof sinon
=== "undefined") {
4338 function makeApi(sinon
) {
4339 sinon
.Event
= function Event(type
, bubbles
, cancelable
, target
) {
4340 this.initEvent(type
, bubbles
, cancelable
, target
);
4343 sinon
.Event
.prototype = {
4344 initEvent: function (type
, bubbles
, cancelable
, target
) {
4346 this.bubbles
= bubbles
;
4347 this.cancelable
= cancelable
;
4348 this.target
= target
;
4351 stopPropagation: function () {},
4353 preventDefault: function () {
4354 this.defaultPrevented
= true;
4358 sinon
.ProgressEvent
= function ProgressEvent(type
, progressEventRaw
, target
) {
4359 this.initEvent(type
, false, false, target
);
4360 this.loaded
= typeof progressEventRaw
.loaded
=== "number" ? progressEventRaw
.loaded
: null;
4361 this.total
= typeof progressEventRaw
.total
=== "number" ? progressEventRaw
.total
: null;
4362 this.lengthComputable
= !!progressEventRaw
.total
;
4365 sinon
.ProgressEvent
.prototype = new sinon
.Event();
4367 sinon
.ProgressEvent
.prototype.constructor = sinon
.ProgressEvent
;
4369 sinon
.CustomEvent
= function CustomEvent(type
, customData
, target
) {
4370 this.initEvent(type
, false, false, target
);
4371 this.detail
= customData
.detail
|| null;
4374 sinon
.CustomEvent
.prototype = new sinon
.Event();
4376 sinon
.CustomEvent
.prototype.constructor = sinon
.CustomEvent
;
4378 sinon
.EventTarget
= {
4379 addEventListener
: function addEventListener(event
, listener
) {
4380 this.eventListeners
= this.eventListeners
|| {};
4381 this.eventListeners
[event
] = this.eventListeners
[event
] || [];
4382 push
.call(this.eventListeners
[event
], listener
);
4385 removeEventListener
: function removeEventListener(event
, listener
) {
4386 var listeners
= this.eventListeners
&& this.eventListeners
[event
] || [];
4388 for (var i
= 0, l
= listeners
.length
; i
< l
; ++i
) {
4389 if (listeners
[i
] === listener
) {
4390 return listeners
.splice(i
, 1);
4395 dispatchEvent
: function dispatchEvent(event
) {
4396 var type
= event
.type
;
4397 var listeners
= this.eventListeners
&& this.eventListeners
[type
] || [];
4399 for (var i
= 0; i
< listeners
.length
; i
++) {
4400 if (typeof listeners
[i
] === "function") {
4401 listeners
[i
].call(this, event
);
4403 listeners
[i
].handleEvent(event
);
4407 return !!event
.defaultPrevented
;
4412 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
4413 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
4415 function loadDependencies(require
) {
4416 var sinon
= require("./core");
4421 define(loadDependencies
);
4422 } else if (isNode
) {
4423 loadDependencies(require
);
4425 makeApi(sinon
); // eslint-disable-line no-undef
4430 * @depend util/core.js
4435 * @author Christian Johansen (christian@cjohansen.no)
4438 * Copyright (c) 2010-2014 Christian Johansen
4440 (function (sinonGlobal
) {
4442 // cache a reference to setTimeout, so that our reference won't be stubbed out
4443 // when using fake timers and errors will still get logged
4444 // https://github.com/cjohansen/Sinon.JS/issues/381
4445 var realSetTimeout
= setTimeout
;
4447 function makeApi(sinon
) {
4451 function logError(label
, err
) {
4452 var msg
= label
+ " threw exception: ";
4454 function throwLoggedError() {
4455 err
.message
= msg
+ err
.message
;
4459 sinon
.log(msg
+ "[" + err
.name
+ "] " + err
.message
);
4462 sinon
.log(err
.stack
);
4465 if (logError
.useImmediateExceptions
) {
4468 logError
.setTimeout(throwLoggedError
, 0);
4472 // When set to true, any errors logged will be thrown immediately;
4473 // If set to false, the errors will be thrown in separate execution frame.
4474 logError
.useImmediateExceptions
= false;
4476 // wrap realSetTimeout with something we can stub in tests
4477 logError
.setTimeout = function (func
, timeout
) {
4478 realSetTimeout(func
, timeout
);
4482 exports
.log
= sinon
.log
= log
;
4483 exports
.logError
= sinon
.logError
= logError
;
4488 function loadDependencies(require
, exports
, module
) {
4489 var sinon
= require("./util/core");
4490 module
.exports
= makeApi(sinon
);
4493 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
4494 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
4497 define(loadDependencies
);
4502 loadDependencies(require
, module
.exports
, module
);
4507 makeApi(sinonGlobal
);
4510 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
4515 * @depend ../extend.js
4517 * @depend ../log_error.js
4520 * Fake XDomainRequest object
4524 * Returns the global to prevent assigning values to 'this' when this is undefined.
4525 * This can occur when files are interpreted by node in strict mode.
4528 function getGlobal() {
4530 return typeof window
!== "undefined" ? window
: global
;
4533 if (typeof sinon
=== "undefined") {
4534 if (typeof this === "undefined") {
4535 getGlobal().sinon
= {};
4541 // wrapper for global
4542 (function (global
) {
4544 var xdr
= { XDomainRequest
: global
.XDomainRequest
};
4545 xdr
.GlobalXDomainRequest
= global
.XDomainRequest
;
4546 xdr
.supportsXDR
= typeof xdr
.GlobalXDomainRequest
!== "undefined";
4547 xdr
.workingXDR
= xdr
.supportsXDR
? xdr
.GlobalXDomainRequest
: false;
4549 function makeApi(sinon
) {
4552 function FakeXDomainRequest() {
4553 this.readyState
= FakeXDomainRequest
.UNSENT
;
4554 this.requestBody
= null;
4555 this.requestHeaders
= {};
4557 this.timeout
= null;
4559 if (typeof FakeXDomainRequest
.onCreate
=== "function") {
4560 FakeXDomainRequest
.onCreate(this);
4564 function verifyState(x
) {
4565 if (x
.readyState
!== FakeXDomainRequest
.OPENED
) {
4566 throw new Error("INVALID_STATE_ERR");
4570 throw new Error("INVALID_STATE_ERR");
4574 function verifyRequestSent(x
) {
4575 if (x
.readyState
=== FakeXDomainRequest
.UNSENT
) {
4576 throw new Error("Request not sent");
4578 if (x
.readyState
=== FakeXDomainRequest
.DONE
) {
4579 throw new Error("Request done");
4583 function verifyResponseBodyType(body
) {
4584 if (typeof body
!== "string") {
4585 var error
= new Error("Attempted to respond to fake XDomainRequest with " +
4586 body
+ ", which is not a string.");
4587 error
.name
= "InvalidBodyException";
4592 sinon
.extend(FakeXDomainRequest
.prototype, sinon
.EventTarget
, {
4593 open
: function open(method
, url
) {
4594 this.method
= method
;
4597 this.responseText
= null;
4598 this.sendFlag
= false;
4600 this.readyStateChange(FakeXDomainRequest
.OPENED
);
4603 readyStateChange
: function readyStateChange(state
) {
4604 this.readyState
= state
;
4606 switch (this.readyState
) {
4607 case FakeXDomainRequest
.UNSENT
:
4609 case FakeXDomainRequest
.OPENED
:
4611 case FakeXDomainRequest
.LOADING
:
4612 if (this.sendFlag
) {
4613 //raise the progress event
4614 eventName
= "onprogress";
4617 case FakeXDomainRequest
.DONE
:
4618 if (this.isTimeout
) {
4619 eventName
= "ontimeout";
4620 } else if (this.errorFlag
|| (this.status
< 200 || this.status
> 299)) {
4621 eventName
= "onerror";
4623 eventName
= "onload";
4628 // raising event (if defined)
4630 if (typeof this[eventName
] === "function") {
4634 sinon
.logError("Fake XHR " + eventName
+ " handler", e
);
4640 send
: function send(data
) {
4643 if (!/^(get|head)$/i.test(this.method
)) {
4644 this.requestBody
= data
;
4646 this.requestHeaders
["Content-Type"] = "text/plain;charset=utf-8";
4648 this.errorFlag
= false;
4649 this.sendFlag
= true;
4650 this.readyStateChange(FakeXDomainRequest
.OPENED
);
4652 if (typeof this.onSend
=== "function") {
4657 abort
: function abort() {
4658 this.aborted
= true;
4659 this.responseText
= null;
4660 this.errorFlag
= true;
4662 if (this.readyState
> sinon
.FakeXDomainRequest
.UNSENT
&& this.sendFlag
) {
4663 this.readyStateChange(sinon
.FakeXDomainRequest
.DONE
);
4664 this.sendFlag
= false;
4668 setResponseBody
: function setResponseBody(body
) {
4669 verifyRequestSent(this);
4670 verifyResponseBodyType(body
);
4672 var chunkSize
= this.chunkSize
|| 10;
4674 this.responseText
= "";
4677 this.readyStateChange(FakeXDomainRequest
.LOADING
);
4678 this.responseText
+= body
.substring(index
, index
+ chunkSize
);
4680 } while (index
< body
.length
);
4682 this.readyStateChange(FakeXDomainRequest
.DONE
);
4685 respond
: function respond(status
, contentType
, body
) {
4686 // content-type ignored, since XDomainRequest does not carry this
4687 // we keep the same syntax for respond(...) as for FakeXMLHttpRequest to ease
4688 // test integration across browsers
4689 this.status
= typeof status
=== "number" ? status
: 200;
4690 this.setResponseBody(body
|| "");
4693 simulatetimeout
: function simulatetimeout() {
4695 this.isTimeout
= true;
4696 // Access to this should actually throw an error
4697 this.responseText
= undefined;
4698 this.readyStateChange(FakeXDomainRequest
.DONE
);
4702 sinon
.extend(FakeXDomainRequest
, {
4709 sinon
.useFakeXDomainRequest
= function useFakeXDomainRequest() {
4710 sinon
.FakeXDomainRequest
.restore
= function restore(keepOnCreate
) {
4711 if (xdr
.supportsXDR
) {
4712 global
.XDomainRequest
= xdr
.GlobalXDomainRequest
;
4715 delete sinon
.FakeXDomainRequest
.restore
;
4717 if (keepOnCreate
!== true) {
4718 delete sinon
.FakeXDomainRequest
.onCreate
;
4721 if (xdr
.supportsXDR
) {
4722 global
.XDomainRequest
= sinon
.FakeXDomainRequest
;
4724 return sinon
.FakeXDomainRequest
;
4727 sinon
.FakeXDomainRequest
= FakeXDomainRequest
;
4730 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
4731 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
4733 function loadDependencies(require
, exports
, module
) {
4734 var sinon
= require("./core");
4735 require("../extend");
4737 require("../log_error");
4739 module
.exports
= sinon
;
4743 define(loadDependencies
);
4744 } else if (isNode
) {
4745 loadDependencies(require
, module
.exports
, module
);
4747 makeApi(sinon
); // eslint-disable-line no-undef
4749 })(typeof global
!== "undefined" ? global
: self
);
4753 * @depend ../extend.js
4755 * @depend ../log_error.js
4758 * Fake XMLHttpRequest object
4760 * @author Christian Johansen (christian@cjohansen.no)
4763 * Copyright (c) 2010-2013 Christian Johansen
4765 (function (sinonGlobal
, global
) {
4767 function getWorkingXHR(globalScope
) {
4768 var supportsXHR
= typeof globalScope
.XMLHttpRequest
!== "undefined";
4770 return globalScope
.XMLHttpRequest
;
4773 var supportsActiveX
= typeof globalScope
.ActiveXObject
!== "undefined";
4774 if (supportsActiveX
) {
4775 return function () {
4776 return new globalScope
.ActiveXObject("MSXML2.XMLHTTP.3.0");
4783 var supportsProgress
= typeof ProgressEvent
!== "undefined";
4784 var supportsCustomEvent
= typeof CustomEvent
!== "undefined";
4785 var supportsFormData
= typeof FormData
!== "undefined";
4786 var supportsArrayBuffer
= typeof ArrayBuffer
!== "undefined";
4787 var supportsBlob
= (function () {
4789 return !!new Blob();
4794 var sinonXhr
= { XMLHttpRequest
: global
.XMLHttpRequest
};
4795 sinonXhr
.GlobalXMLHttpRequest
= global
.XMLHttpRequest
;
4796 sinonXhr
.GlobalActiveXObject
= global
.ActiveXObject
;
4797 sinonXhr
.supportsActiveX
= typeof sinonXhr
.GlobalActiveXObject
!== "undefined";
4798 sinonXhr
.supportsXHR
= typeof sinonXhr
.GlobalXMLHttpRequest
!== "undefined";
4799 sinonXhr
.workingXHR
= getWorkingXHR(global
);
4800 sinonXhr
.supportsCORS
= sinonXhr
.supportsXHR
&& "withCredentials" in (new sinonXhr
.GlobalXMLHttpRequest());
4802 var unsafeHeaders
= {
4803 "Accept-Charset": true,
4804 "Accept-Encoding": true,
4806 "Content-Length": true,
4809 "Content-Transfer-Encoding": true,
4817 "Transfer-Encoding": true,
4823 // An upload object is created for each
4824 // FakeXMLHttpRequest and allows upload
4825 // events to be simulated using uploadProgress
4827 function UploadProgress() {
4828 this.eventListeners
= {
4837 UploadProgress
.prototype.addEventListener
= function addEventListener(event
, listener
) {
4838 this.eventListeners
[event
].push(listener
);
4841 UploadProgress
.prototype.removeEventListener
= function removeEventListener(event
, listener
) {
4842 var listeners
= this.eventListeners
[event
] || [];
4844 for (var i
= 0, l
= listeners
.length
; i
< l
; ++i
) {
4845 if (listeners
[i
] === listener
) {
4846 return listeners
.splice(i
, 1);
4851 UploadProgress
.prototype.dispatchEvent
= function dispatchEvent(event
) {
4852 var listeners
= this.eventListeners
[event
.type
] || [];
4854 for (var i
= 0, listener
; (listener
= listeners
[i
]) != null; i
++) {
4859 // Note that for FakeXMLHttpRequest to work pre ES5
4860 // we lose some of the alignment with the spec.
4861 // To ensure as close a match as possible,
4862 // set responseType before calling open, send or respond;
4863 function FakeXMLHttpRequest() {
4864 this.readyState
= FakeXMLHttpRequest
.UNSENT
;
4865 this.requestHeaders
= {};
4866 this.requestBody
= null;
4868 this.statusText
= "";
4869 this.upload
= new UploadProgress();
4870 this.responseType
= "";
4872 if (sinonXhr
.supportsCORS
) {
4873 this.withCredentials
= false;
4877 var events
= ["loadstart", "load", "abort", "error", "loadend"];
4879 function addEventListener(eventName
) {
4880 xhr
.addEventListener(eventName
, function (event
) {
4881 var listener
= xhr
["on" + eventName
];
4883 if (listener
&& typeof listener
=== "function") {
4884 listener
.call(this, event
);
4889 for (var i
= events
.length
- 1; i
>= 0; i
--) {
4890 addEventListener(events
[i
]);
4893 if (typeof FakeXMLHttpRequest
.onCreate
=== "function") {
4894 FakeXMLHttpRequest
.onCreate(this);
4898 function verifyState(xhr
) {
4899 if (xhr
.readyState
!== FakeXMLHttpRequest
.OPENED
) {
4900 throw new Error("INVALID_STATE_ERR");
4904 throw new Error("INVALID_STATE_ERR");
4908 function getHeader(headers
, header
) {
4909 header
= header
.toLowerCase();
4911 for (var h
in headers
) {
4912 if (h
.toLowerCase() === header
) {
4920 // filtering to enable a white-list version of Sinon FakeXhr,
4921 // where whitelisted requests are passed through to real XHR
4922 function each(collection
, callback
) {
4927 for (var i
= 0, l
= collection
.length
; i
< l
; i
+= 1) {
4928 callback(collection
[i
]);
4931 function some(collection
, callback
) {
4932 for (var index
= 0; index
< collection
.length
; index
++) {
4933 if (callback(collection
[index
]) === true) {
4939 // largest arity in XHR is 5 - XHR#open
4940 var apply = function (obj
, method
, args
) {
4941 switch (args
.length
) {
4942 case 0: return obj
[method
]();
4943 case 1: return obj
[method
](args
[0]);
4944 case 2: return obj
[method
](args
[0], args
[1]);
4945 case 3: return obj
[method
](args
[0], args
[1], args
[2]);
4946 case 4: return obj
[method
](args
[0], args
[1], args
[2], args
[3]);
4947 case 5: return obj
[method
](args
[0], args
[1], args
[2], args
[3], args
[4]);
4951 FakeXMLHttpRequest
.filters
= [];
4952 FakeXMLHttpRequest
.addFilter
= function addFilter(fn
) {
4953 this.filters
.push(fn
);
4955 var IE6Re
= /MSIE 6/;
4956 FakeXMLHttpRequest
.defake
= function defake(fakeXhr
, xhrArgs
) {
4957 var xhr
= new sinonXhr
.workingXHR(); // eslint-disable-line new-cap
4964 "getResponseHeader",
4965 "getAllResponseHeaders",
4968 "removeEventListener"
4969 ], function (method
) {
4970 fakeXhr
[method
] = function () {
4971 return apply(xhr
, method
, arguments
);
4975 var copyAttrs = function (args
) {
4976 each(args
, function (attr
) {
4978 fakeXhr
[attr
] = xhr
[attr
];
4980 if (!IE6Re
.test(navigator
.userAgent
)) {
4987 var stateChange
= function stateChange() {
4988 fakeXhr
.readyState
= xhr
.readyState
;
4989 if (xhr
.readyState
>= FakeXMLHttpRequest
.HEADERS_RECEIVED
) {
4990 copyAttrs(["status", "statusText"]);
4992 if (xhr
.readyState
>= FakeXMLHttpRequest
.LOADING
) {
4993 copyAttrs(["responseText", "response"]);
4995 if (xhr
.readyState
=== FakeXMLHttpRequest
.DONE
) {
4996 copyAttrs(["responseXML"]);
4998 if (fakeXhr
.onreadystatechange
) {
4999 fakeXhr
.onreadystatechange
.call(fakeXhr
, { target
: fakeXhr
});
5003 if (xhr
.addEventListener
) {
5004 for (var event
in fakeXhr
.eventListeners
) {
5005 if (fakeXhr
.eventListeners
.hasOwnProperty(event
)) {
5007 /*eslint-disable no-loop-func*/
5008 each(fakeXhr
.eventListeners
[event
], function (handler
) {
5009 xhr
.addEventListener(event
, handler
);
5011 /*eslint-enable no-loop-func*/
5014 xhr
.addEventListener("readystatechange", stateChange
);
5016 xhr
.onreadystatechange
= stateChange
;
5018 apply(xhr
, "open", xhrArgs
);
5020 FakeXMLHttpRequest
.useFilters
= false;
5022 function verifyRequestOpened(xhr
) {
5023 if (xhr
.readyState
!== FakeXMLHttpRequest
.OPENED
) {
5024 throw new Error("INVALID_STATE_ERR - " + xhr
.readyState
);
5028 function verifyRequestSent(xhr
) {
5029 if (xhr
.readyState
=== FakeXMLHttpRequest
.DONE
) {
5030 throw new Error("Request done");
5034 function verifyHeadersReceived(xhr
) {
5035 if (xhr
.async
&& xhr
.readyState
!== FakeXMLHttpRequest
.HEADERS_RECEIVED
) {
5036 throw new Error("No headers received");
5040 function verifyResponseBodyType(body
) {
5041 if (typeof body
!== "string") {
5042 var error
= new Error("Attempted to respond to fake XMLHttpRequest with " +
5043 body
+ ", which is not a string.");
5044 error
.name
= "InvalidBodyException";
5049 function convertToArrayBuffer(body
) {
5050 var buffer
= new ArrayBuffer(body
.length
);
5051 var view
= new Uint8Array(buffer
);
5052 for (var i
= 0; i
< body
.length
; i
++) {
5053 var charCode
= body
.charCodeAt(i
);
5054 if (charCode
>= 256) {
5055 throw new TypeError("arraybuffer or blob responseTypes require binary string, " +
5056 "invalid character " + body
[i
] + " found.");
5063 function isXmlContentType(contentType
) {
5064 return !contentType
|| /(text\/xml)|(application\/xml)|(\+xml)/.test(contentType
);
5067 function convertResponseBody(responseType
, contentType
, body
) {
5068 if (responseType
=== "" || responseType
=== "text") {
5070 } else if (supportsArrayBuffer
&& responseType
=== "arraybuffer") {
5071 return convertToArrayBuffer(body
);
5072 } else if (responseType
=== "json") {
5074 return JSON
.parse(body
);
5076 // Return parsing failure as null
5079 } else if (supportsBlob
&& responseType
=== "blob") {
5080 var blobOptions
= {};
5082 blobOptions
.type
= contentType
;
5084 return new Blob([convertToArrayBuffer(body
)], blobOptions
);
5085 } else if (responseType
=== "document") {
5086 if (isXmlContentType(contentType
)) {
5087 return FakeXMLHttpRequest
.parseXML(body
);
5091 throw new Error("Invalid responseType " + responseType
);
5094 function clearResponse(xhr
) {
5095 if (xhr
.responseType
=== "" || xhr
.responseType
=== "text") {
5096 xhr
.response
= xhr
.responseText
= "";
5098 xhr
.response
= xhr
.responseText
= null;
5100 xhr
.responseXML
= null;
5103 FakeXMLHttpRequest
.parseXML
= function parseXML(text
) {
5104 // Treat empty string as parsing failure
5107 if (typeof DOMParser
!== "undefined") {
5108 var parser
= new DOMParser();
5109 return parser
.parseFromString(text
, "text/xml");
5111 var xmlDoc
= new window
.ActiveXObject("Microsoft.XMLDOM");
5112 xmlDoc
.async
= "false";
5113 xmlDoc
.loadXML(text
);
5116 // Unable to parse XML - no biggie
5123 FakeXMLHttpRequest
.statusCodes
= {
5125 101: "Switching Protocols",
5129 203: "Non-Authoritative Information",
5131 205: "Reset Content",
5132 206: "Partial Content",
5133 207: "Multi-Status",
5134 300: "Multiple Choice",
5135 301: "Moved Permanently",
5138 304: "Not Modified",
5140 307: "Temporary Redirect",
5142 401: "Unauthorized",
5143 402: "Payment Required",
5146 405: "Method Not Allowed",
5147 406: "Not Acceptable",
5148 407: "Proxy Authentication Required",
5149 408: "Request Timeout",
5152 411: "Length Required",
5153 412: "Precondition Failed",
5154 413: "Request Entity Too Large",
5155 414: "Request-URI Too Long",
5156 415: "Unsupported Media Type",
5157 416: "Requested Range Not Satisfiable",
5158 417: "Expectation Failed",
5159 422: "Unprocessable Entity",
5160 500: "Internal Server Error",
5161 501: "Not Implemented",
5163 503: "Service Unavailable",
5164 504: "Gateway Timeout",
5165 505: "HTTP Version Not Supported"
5168 function makeApi(sinon
) {
5169 sinon
.xhr
= sinonXhr
;
5171 sinon
.extend(FakeXMLHttpRequest
.prototype, sinon
.EventTarget
, {
5174 open
: function open(method
, url
, async
, username
, password
) {
5175 this.method
= method
;
5177 this.async
= typeof async
=== "boolean" ? async
: true;
5178 this.username
= username
;
5179 this.password
= password
;
5180 clearResponse(this);
5181 this.requestHeaders
= {};
5182 this.sendFlag
= false;
5184 if (FakeXMLHttpRequest
.useFilters
=== true) {
5185 var xhrArgs
= arguments
;
5186 var defake
= some(FakeXMLHttpRequest
.filters
, function (filter
) {
5187 return filter
.apply(this, xhrArgs
);
5190 return FakeXMLHttpRequest
.defake(this, arguments
);
5193 this.readyStateChange(FakeXMLHttpRequest
.OPENED
);
5196 readyStateChange
: function readyStateChange(state
) {
5197 this.readyState
= state
;
5199 var readyStateChangeEvent
= new sinon
.Event("readystatechange", false, false, this);
5200 var event
, progress
;
5202 if (typeof this.onreadystatechange
=== "function") {
5204 this.onreadystatechange(readyStateChangeEvent
);
5206 sinon
.logError("Fake XHR onreadystatechange handler", e
);
5210 if (this.readyState
=== FakeXMLHttpRequest
.DONE
) {
5211 // ensure loaded and total are numbers
5213 loaded
: this.progress
|| 0,
5214 total
: this.progress
|| 0
5217 if (this.status
=== 0) {
5218 event
= this.aborted
? "abort" : "error";
5224 if (supportsProgress
) {
5225 this.upload
.dispatchEvent(new sinon
.ProgressEvent("progress", progress
, this));
5226 this.upload
.dispatchEvent(new sinon
.ProgressEvent(event
, progress
, this));
5227 this.upload
.dispatchEvent(new sinon
.ProgressEvent("loadend", progress
, this));
5230 this.dispatchEvent(new sinon
.ProgressEvent("progress", progress
, this));
5231 this.dispatchEvent(new sinon
.ProgressEvent(event
, progress
, this));
5232 this.dispatchEvent(new sinon
.ProgressEvent("loadend", progress
, this));
5235 this.dispatchEvent(readyStateChangeEvent
);
5238 setRequestHeader
: function setRequestHeader(header
, value
) {
5241 if (unsafeHeaders
[header
] || /^(Sec-|Proxy-)/.test(header
)) {
5242 throw new Error("Refused to set unsafe header \"" + header
+ "\"");
5245 if (this.requestHeaders
[header
]) {
5246 this.requestHeaders
[header
] += "," + value
;
5248 this.requestHeaders
[header
] = value
;
5253 setResponseHeaders
: function setResponseHeaders(headers
) {
5254 verifyRequestOpened(this);
5255 this.responseHeaders
= {};
5257 for (var header
in headers
) {
5258 if (headers
.hasOwnProperty(header
)) {
5259 this.responseHeaders
[header
] = headers
[header
];
5264 this.readyStateChange(FakeXMLHttpRequest
.HEADERS_RECEIVED
);
5266 this.readyState
= FakeXMLHttpRequest
.HEADERS_RECEIVED
;
5270 // Currently treats ALL data as a DOMString (i.e. no Document)
5271 send
: function send(data
) {
5274 if (!/^(get|head)$/i.test(this.method
)) {
5275 var contentType
= getHeader(this.requestHeaders
, "Content-Type");
5276 if (this.requestHeaders
[contentType
]) {
5277 var value
= this.requestHeaders
[contentType
].split(";");
5278 this.requestHeaders
[contentType
] = value
[0] + ";charset=utf-8";
5279 } else if (supportsFormData
&& !(data
instanceof FormData
)) {
5280 this.requestHeaders
["Content-Type"] = "text/plain;charset=utf-8";
5283 this.requestBody
= data
;
5286 this.errorFlag
= false;
5287 this.sendFlag
= this.async
;
5288 clearResponse(this);
5289 this.readyStateChange(FakeXMLHttpRequest
.OPENED
);
5291 if (typeof this.onSend
=== "function") {
5295 this.dispatchEvent(new sinon
.Event("loadstart", false, false, this));
5298 abort
: function abort() {
5299 this.aborted
= true;
5300 clearResponse(this);
5301 this.errorFlag
= true;
5302 this.requestHeaders
= {};
5303 this.responseHeaders
= {};
5305 if (this.readyState
> FakeXMLHttpRequest
.UNSENT
&& this.sendFlag
) {
5306 this.readyStateChange(FakeXMLHttpRequest
.DONE
);
5307 this.sendFlag
= false;
5310 this.readyState
= FakeXMLHttpRequest
.UNSENT
;
5313 error
: function error() {
5314 clearResponse(this);
5315 this.errorFlag
= true;
5316 this.requestHeaders
= {};
5317 this.responseHeaders
= {};
5319 this.readyStateChange(FakeXMLHttpRequest
.DONE
);
5322 getResponseHeader
: function getResponseHeader(header
) {
5323 if (this.readyState
< FakeXMLHttpRequest
.HEADERS_RECEIVED
) {
5327 if (/^Set-Cookie2?$/i.test(header
)) {
5331 header
= getHeader(this.responseHeaders
, header
);
5333 return this.responseHeaders
[header
] || null;
5336 getAllResponseHeaders
: function getAllResponseHeaders() {
5337 if (this.readyState
< FakeXMLHttpRequest
.HEADERS_RECEIVED
) {
5343 for (var header
in this.responseHeaders
) {
5344 if (this.responseHeaders
.hasOwnProperty(header
) &&
5345 !/^Set-Cookie2?$/i.test(header
)) {
5346 headers
+= header
+ ": " + this.responseHeaders
[header
] + "\r\n";
5353 setResponseBody
: function setResponseBody(body
) {
5354 verifyRequestSent(this);
5355 verifyHeadersReceived(this);
5356 verifyResponseBodyType(body
);
5357 var contentType
= this.getResponseHeader("Content-Type");
5359 var isTextResponse
= this.responseType
=== "" || this.responseType
=== "text";
5360 clearResponse(this);
5362 var chunkSize
= this.chunkSize
|| 10;
5366 this.readyStateChange(FakeXMLHttpRequest
.LOADING
);
5368 if (isTextResponse
) {
5369 this.responseText
= this.response
+= body
.substring(index
, index
+ chunkSize
);
5372 } while (index
< body
.length
);
5375 this.response
= convertResponseBody(this.responseType
, contentType
, body
);
5376 if (isTextResponse
) {
5377 this.responseText
= this.response
;
5380 if (this.responseType
=== "document") {
5381 this.responseXML
= this.response
;
5382 } else if (this.responseType
=== "" && isXmlContentType(contentType
)) {
5383 this.responseXML
= FakeXMLHttpRequest
.parseXML(this.responseText
);
5385 this.progress
= body
.length
;
5386 this.readyStateChange(FakeXMLHttpRequest
.DONE
);
5389 respond
: function respond(status
, headers
, body
) {
5390 this.status
= typeof status
=== "number" ? status
: 200;
5391 this.statusText
= FakeXMLHttpRequest
.statusCodes
[this.status
];
5392 this.setResponseHeaders(headers
|| {});
5393 this.setResponseBody(body
|| "");
5396 uploadProgress
: function uploadProgress(progressEventRaw
) {
5397 if (supportsProgress
) {
5398 this.upload
.dispatchEvent(new sinon
.ProgressEvent("progress", progressEventRaw
));
5402 downloadProgress
: function downloadProgress(progressEventRaw
) {
5403 if (supportsProgress
) {
5404 this.dispatchEvent(new sinon
.ProgressEvent("progress", progressEventRaw
));
5408 uploadError
: function uploadError(error
) {
5409 if (supportsCustomEvent
) {
5410 this.upload
.dispatchEvent(new sinon
.CustomEvent("error", {detail
: error
}));
5415 sinon
.extend(FakeXMLHttpRequest
, {
5418 HEADERS_RECEIVED
: 2,
5423 sinon
.useFakeXMLHttpRequest = function () {
5424 FakeXMLHttpRequest
.restore
= function restore(keepOnCreate
) {
5425 if (sinonXhr
.supportsXHR
) {
5426 global
.XMLHttpRequest
= sinonXhr
.GlobalXMLHttpRequest
;
5429 if (sinonXhr
.supportsActiveX
) {
5430 global
.ActiveXObject
= sinonXhr
.GlobalActiveXObject
;
5433 delete FakeXMLHttpRequest
.restore
;
5435 if (keepOnCreate
!== true) {
5436 delete FakeXMLHttpRequest
.onCreate
;
5439 if (sinonXhr
.supportsXHR
) {
5440 global
.XMLHttpRequest
= FakeXMLHttpRequest
;
5443 if (sinonXhr
.supportsActiveX
) {
5444 global
.ActiveXObject
= function ActiveXObject(objId
) {
5445 if (objId
=== "Microsoft.XMLHTTP" || /^Msxml2\.XMLHTTP/i.test(objId
)) {
5447 return new FakeXMLHttpRequest();
5450 return new sinonXhr
.GlobalActiveXObject(objId
);
5454 return FakeXMLHttpRequest
;
5457 sinon
.FakeXMLHttpRequest
= FakeXMLHttpRequest
;
5460 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
5461 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
5463 function loadDependencies(require
, exports
, module
) {
5464 var sinon
= require("./core");
5465 require("../extend");
5467 require("../log_error");
5469 module
.exports
= sinon
;
5473 define(loadDependencies
);
5478 loadDependencies(require
, module
.exports
, module
);
5483 makeApi(sinonGlobal
);
5486 typeof sinon
=== "object" && sinon
, // eslint-disable-line no-undef
5487 typeof global
!== "undefined" ? global
: self
5491 * @depend fake_xdomain_request.js
5492 * @depend fake_xml_http_request.js
5493 * @depend ../format.js
5494 * @depend ../log_error.js
5497 * The Sinon "server" mimics a web server that receives requests from
5498 * sinon.FakeXMLHttpRequest and provides an API to respond to those requests,
5499 * both synchronously and asynchronously. To respond synchronuously, canned
5500 * answers have to be provided upfront.
5502 * @author Christian Johansen (christian@cjohansen.no)
5505 * Copyright (c) 2010-2013 Christian Johansen
5511 function responseArray(handler
) {
5512 var response
= handler
;
5514 if (Object
.prototype.toString
.call(handler
) !== "[object Array]") {
5515 response
= [200, {}, handler
];
5518 if (typeof response
[2] !== "string") {
5519 throw new TypeError("Fake server response body should be string, but was " +
5520 typeof response
[2]);
5526 var wloc
= typeof window
!== "undefined" ? window
.location
: {};
5527 var rCurrLoc
= new RegExp("^" + wloc
.protocol
+ "//" + wloc
.host
);
5529 function matchOne(response
, reqMethod
, reqUrl
) {
5530 var rmeth
= response
.method
;
5531 var matchMethod
= !rmeth
|| rmeth
.toLowerCase() === reqMethod
.toLowerCase();
5532 var url
= response
.url
;
5533 var matchUrl
= !url
|| url
=== reqUrl
|| (typeof url
.test
=== "function" && url
.test(reqUrl
));
5535 return matchMethod
&& matchUrl
;
5538 function match(response
, request
) {
5539 var requestUrl
= request
.url
;
5541 if (!/^https?:\/\//.test(requestUrl
) || rCurrLoc
.test(requestUrl
)) {
5542 requestUrl
= requestUrl
.replace(rCurrLoc
, "");
5545 if (matchOne(response
, this.getHTTPMethod(request
), requestUrl
)) {
5546 if (typeof response
.response
=== "function") {
5547 var ru
= response
.url
;
5548 var args
= [request
].concat(ru
&& typeof ru
.exec
=== "function" ? ru
.exec(requestUrl
).slice(1) : []);
5549 return response
.response
.apply(response
, args
);
5558 function makeApi(sinon
) {
5559 sinon
.fakeServer
= {
5560 create: function (config
) {
5561 var server
= sinon
.create(this);
5562 server
.configure(config
);
5563 if (!sinon
.xhr
.supportsCORS
) {
5564 this.xhr
= sinon
.useFakeXDomainRequest();
5566 this.xhr
= sinon
.useFakeXMLHttpRequest();
5568 server
.requests
= [];
5570 this.xhr
.onCreate = function (xhrObj
) {
5571 server
.addRequest(xhrObj
);
5576 configure: function (config
) {
5578 "autoRespond": true,
5579 "autoRespondAfter": true,
5580 "respondImmediately": true,
5581 "fakeHTTPMethods": true
5585 config
= config
|| {};
5586 for (setting
in config
) {
5587 if (whitelist
.hasOwnProperty(setting
) && config
.hasOwnProperty(setting
)) {
5588 this[setting
] = config
[setting
];
5592 addRequest
: function addRequest(xhrObj
) {
5594 push
.call(this.requests
, xhrObj
);
5596 xhrObj
.onSend = function () {
5597 server
.handleRequest(this);
5599 if (server
.respondImmediately
) {
5601 } else if (server
.autoRespond
&& !server
.responding
) {
5602 setTimeout(function () {
5603 server
.responding
= false;
5605 }, server
.autoRespondAfter
|| 10);
5607 server
.responding
= true;
5612 getHTTPMethod
: function getHTTPMethod(request
) {
5613 if (this.fakeHTTPMethods
&& /post/i.test(request
.method
)) {
5614 var matches
= (request
.requestBody
|| "").match(/_method=([^\b;]+)/);
5615 return matches
? matches
[1] : request
.method
;
5618 return request
.method
;
5621 handleRequest
: function handleRequest(xhr
) {
5627 push
.call(this.queue
, xhr
);
5629 this.processRequest(xhr
);
5633 log
: function log(response
, request
) {
5636 str
= "Request:\n" + sinon
.format(request
) + "\n\n";
5637 str
+= "Response:\n" + sinon
.format(response
) + "\n\n";
5642 respondWith
: function respondWith(method
, url
, body
) {
5643 if (arguments
.length
=== 1 && typeof method
!== "function") {
5644 this.response
= responseArray(method
);
5648 if (!this.responses
) {
5649 this.responses
= [];
5652 if (arguments
.length
=== 1) {
5654 url
= method
= null;
5657 if (arguments
.length
=== 2) {
5663 push
.call(this.responses
, {
5666 response
: typeof body
=== "function" ? body
: responseArray(body
)
5670 respond
: function respond() {
5671 if (arguments
.length
> 0) {
5672 this.respondWith
.apply(this, arguments
);
5675 var queue
= this.queue
|| [];
5676 var requests
= queue
.splice(0, queue
.length
);
5678 for (var i
= 0; i
< requests
.length
; i
++) {
5679 this.processRequest(requests
[i
]);
5683 processRequest
: function processRequest(request
) {
5685 if (request
.aborted
) {
5689 var response
= this.response
|| [404, {}, ""];
5691 if (this.responses
) {
5692 for (var l
= this.responses
.length
, i
= l
- 1; i
>= 0; i
--) {
5693 if (match
.call(this, this.responses
[i
], request
)) {
5694 response
= this.responses
[i
].response
;
5700 if (request
.readyState
!== 4) {
5701 this.log(response
, request
);
5703 request
.respond(response
[0], response
[1], response
[2]);
5706 sinon
.logError("Fake server request processing", e
);
5710 restore
: function restore() {
5711 return this.xhr
.restore
&& this.xhr
.restore
.apply(this.xhr
, arguments
);
5716 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
5717 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
5719 function loadDependencies(require
, exports
, module
) {
5720 var sinon
= require("./core");
5721 require("./fake_xdomain_request");
5722 require("./fake_xml_http_request");
5723 require("../format");
5725 module
.exports
= sinon
;
5729 define(loadDependencies
);
5730 } else if (isNode
) {
5731 loadDependencies(require
, module
.exports
, module
);
5733 makeApi(sinon
); // eslint-disable-line no-undef
5738 * @depend fake_server.js
5739 * @depend fake_timers.js
5742 * Add-on for sinon.fakeServer that automatically handles a fake timer along with
5743 * the FakeXMLHttpRequest. The direct inspiration for this add-on is jQuery
5744 * 1.3.x, which does not use xhr object's onreadystatehandler at all - instead,
5745 * it polls the object for completion with setInterval. Dispite the direct
5746 * motivation, there is nothing jQuery-specific in this file, so it can be used
5747 * in any environment where the ajax implementation depends on setInterval or
5750 * @author Christian Johansen (christian@cjohansen.no)
5753 * Copyright (c) 2010-2013 Christian Johansen
5757 function makeApi(sinon
) {
5758 function Server() {}
5759 Server
.prototype = sinon
.fakeServer
;
5761 sinon
.fakeServerWithClock
= new Server();
5763 sinon
.fakeServerWithClock
.addRequest
= function addRequest(xhr
) {
5765 if (typeof setTimeout
.clock
=== "object") {
5766 this.clock
= setTimeout
.clock
;
5768 this.clock
= sinon
.useFakeTimers();
5769 this.resetClock
= true;
5772 if (!this.longestTimeout
) {
5773 var clockSetTimeout
= this.clock
.setTimeout
;
5774 var clockSetInterval
= this.clock
.setInterval
;
5777 this.clock
.setTimeout = function (fn
, timeout
) {
5778 server
.longestTimeout
= Math
.max(timeout
, server
.longestTimeout
|| 0);
5780 return clockSetTimeout
.apply(this, arguments
);
5783 this.clock
.setInterval = function (fn
, timeout
) {
5784 server
.longestTimeout
= Math
.max(timeout
, server
.longestTimeout
|| 0);
5786 return clockSetInterval
.apply(this, arguments
);
5791 return sinon
.fakeServer
.addRequest
.call(this, xhr
);
5794 sinon
.fakeServerWithClock
.respond
= function respond() {
5795 var returnVal
= sinon
.fakeServer
.respond
.apply(this, arguments
);
5798 this.clock
.tick(this.longestTimeout
|| 0);
5799 this.longestTimeout
= 0;
5801 if (this.resetClock
) {
5802 this.clock
.restore();
5803 this.resetClock
= false;
5810 sinon
.fakeServerWithClock
.restore
= function restore() {
5812 this.clock
.restore();
5815 return sinon
.fakeServer
.restore
.apply(this, arguments
);
5819 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
5820 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
5822 function loadDependencies(require
) {
5823 var sinon
= require("./core");
5824 require("./fake_server");
5825 require("./fake_timers");
5830 define(loadDependencies
);
5831 } else if (isNode
) {
5832 loadDependencies(require
);
5834 makeApi(sinon
); // eslint-disable-line no-undef
5839 * @depend util/core.js
5841 * @depend collection.js
5842 * @depend util/fake_timers.js
5843 * @depend util/fake_server_with_clock.js
5846 * Manages fake collections as well as fake utilities such as Sinon's
5847 * timers and fake XHR implementation in one convenient object.
5849 * @author Christian Johansen (christian@cjohansen.no)
5852 * Copyright (c) 2010-2013 Christian Johansen
5854 (function (sinonGlobal
) {
5856 function makeApi(sinon
) {
5859 function exposeValue(sandbox
, config
, key
, value
) {
5864 if (config
.injectInto
&& !(key
in config
.injectInto
)) {
5865 config
.injectInto
[key
] = value
;
5866 sandbox
.injectedKeys
.push(key
);
5868 push
.call(sandbox
.args
, value
);
5872 function prepareSandboxFromConfig(config
) {
5873 var sandbox
= sinon
.create(sinon
.sandbox
);
5875 if (config
.useFakeServer
) {
5876 if (typeof config
.useFakeServer
=== "object") {
5877 sandbox
.serverPrototype
= config
.useFakeServer
;
5880 sandbox
.useFakeServer();
5883 if (config
.useFakeTimers
) {
5884 if (typeof config
.useFakeTimers
=== "object") {
5885 sandbox
.useFakeTimers
.apply(sandbox
, config
.useFakeTimers
);
5887 sandbox
.useFakeTimers();
5894 sinon
.sandbox
= sinon
.extend(sinon
.create(sinon
.collection
), {
5895 useFakeTimers
: function useFakeTimers() {
5896 this.clock
= sinon
.useFakeTimers
.apply(sinon
, arguments
);
5898 return this.add(this.clock
);
5901 serverPrototype
: sinon
.fakeServer
,
5903 useFakeServer
: function useFakeServer() {
5904 var proto
= this.serverPrototype
|| sinon
.fakeServer
;
5906 if (!proto
|| !proto
.create
) {
5910 this.server
= proto
.create();
5911 return this.add(this.server
);
5914 inject: function (obj
) {
5915 sinon
.collection
.inject
.call(this, obj
);
5918 obj
.clock
= this.clock
;
5922 obj
.server
= this.server
;
5923 obj
.requests
= this.server
.requests
;
5926 obj
.match
= sinon
.match
;
5931 restore: function () {
5932 if (arguments
.length
) {
5933 throw new Error("sandbox.restore() does not take any parameters. Perhaps you meant stub.restore()");
5936 sinon
.collection
.restore
.apply(this, arguments
);
5937 this.restoreContext();
5940 restoreContext: function () {
5941 if (this.injectedKeys
) {
5942 for (var i
= 0, j
= this.injectedKeys
.length
; i
< j
; i
++) {
5943 delete this.injectInto
[this.injectedKeys
[i
]];
5945 this.injectedKeys
= [];
5949 create: function (config
) {
5951 return sinon
.create(sinon
.sandbox
);
5954 var sandbox
= prepareSandboxFromConfig(config
);
5955 sandbox
.args
= sandbox
.args
|| [];
5956 sandbox
.injectedKeys
= [];
5957 sandbox
.injectInto
= config
.injectInto
;
5960 var exposed
= sandbox
.inject({});
5962 if (config
.properties
) {
5963 for (var i
= 0, l
= config
.properties
.length
; i
< l
; i
++) {
5964 prop
= config
.properties
[i
];
5965 value
= exposed
[prop
] || prop
=== "sandbox" && sandbox
;
5966 exposeValue(sandbox
, config
, prop
, value
);
5969 exposeValue(sandbox
, config
, "sandbox", value
);
5978 sinon
.sandbox
.useFakeXMLHttpRequest
= sinon
.sandbox
.useFakeServer
;
5980 return sinon
.sandbox
;
5983 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
5984 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
5986 function loadDependencies(require
, exports
, module
) {
5987 var sinon
= require("./util/core");
5988 require("./extend");
5989 require("./util/fake_server_with_clock");
5990 require("./util/fake_timers");
5991 require("./collection");
5992 module
.exports
= makeApi(sinon
);
5996 define(loadDependencies
);
6001 loadDependencies(require
, module
.exports
, module
);
6006 makeApi(sinonGlobal
);
6009 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
6013 * @depend util/core.js
6014 * @depend sandbox.js
6017 * Test function, sandboxes fakes
6019 * @author Christian Johansen (christian@cjohansen.no)
6022 * Copyright (c) 2010-2013 Christian Johansen
6024 (function (sinonGlobal
) {
6026 function makeApi(sinon
) {
6027 var slice
= Array
.prototype.slice
;
6029 function test(callback
) {
6030 var type
= typeof callback
;
6032 if (type
!== "function") {
6033 throw new TypeError("sinon.test needs to wrap a test function, got " + type
);
6036 function sinonSandboxedTest() {
6037 var config
= sinon
.getConfig(sinon
.config
);
6038 config
.injectInto
= config
.injectIntoThis
&& this || config
.injectInto
;
6039 var sandbox
= sinon
.sandbox
.create(config
);
6040 var args
= slice
.call(arguments
);
6041 var oldDone
= args
.length
&& args
[args
.length
- 1];
6042 var exception
, result
;
6044 if (typeof oldDone
=== "function") {
6045 args
[args
.length
- 1] = function sinonDone(res
) {
6049 sandbox
.verifyAndRestore();
6056 result
= callback
.apply(this, args
.concat(sandbox
.args
));
6061 if (typeof exception
!== "undefined") {
6064 } else if (typeof oldDone
!== "function") {
6065 sandbox
.verifyAndRestore();
6071 if (callback
.length
) {
6072 return function sinonAsyncSandboxedTest(done
) { // eslint-disable-line no-unused-vars
6073 return sinonSandboxedTest
.apply(this, arguments
);
6077 return sinonSandboxedTest
;
6081 injectIntoThis
: true,
6083 properties
: ["spy", "stub", "mock", "clock", "server", "requests"],
6084 useFakeTimers
: true,
6092 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
6093 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
6095 function loadDependencies(require
, exports
, module
) {
6096 var core
= require("./util/core");
6097 require("./sandbox");
6098 module
.exports
= makeApi(core
);
6102 define(loadDependencies
);
6103 } else if (isNode
) {
6104 loadDependencies(require
, module
.exports
, module
);
6105 } else if (sinonGlobal
) {
6106 makeApi(sinonGlobal
);
6108 }(typeof sinon
=== "object" && sinon
|| null)); // eslint-disable-line no-undef
6111 * @depend util/core.js
6115 * Test case, sandboxes all test functions
6117 * @author Christian Johansen (christian@cjohansen.no)
6120 * Copyright (c) 2010-2013 Christian Johansen
6122 (function (sinonGlobal
) {
6124 function createTest(property
, setUp
, tearDown
) {
6125 return function () {
6127 setUp
.apply(this, arguments
);
6130 var exception
, result
;
6133 result
= property
.apply(this, arguments
);
6139 tearDown
.apply(this, arguments
);
6150 function makeApi(sinon
) {
6151 function testCase(tests
, prefix
) {
6152 if (!tests
|| typeof tests
!== "object") {
6153 throw new TypeError("sinon.testCase needs an object with test functions");
6156 prefix
= prefix
|| "test";
6157 var rPrefix
= new RegExp("^" + prefix
);
6159 var setUp
= tests
.setUp
;
6160 var tearDown
= tests
.tearDown
;
6165 for (testName
in tests
) {
6166 if (tests
.hasOwnProperty(testName
) && !/^(setUp|tearDown)$/.test(testName
)) {
6167 property
= tests
[testName
];
6169 if (typeof property
=== "function" && rPrefix
.test(testName
)) {
6172 if (setUp
|| tearDown
) {
6173 method
= createTest(property
, setUp
, tearDown
);
6176 methods
[testName
] = sinon
.test(method
);
6178 methods
[testName
] = tests
[testName
];
6186 sinon
.testCase
= testCase
;
6190 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
6191 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
6193 function loadDependencies(require
, exports
, module
) {
6194 var core
= require("./util/core");
6196 module
.exports
= makeApi(core
);
6200 define(loadDependencies
);
6205 loadDependencies(require
, module
.exports
, module
);
6210 makeApi(sinonGlobal
);
6213 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
6217 * @depend times_in_words.js
6218 * @depend util/core.js
6223 * Assertions matching the test spy retrieval interface.
6225 * @author Christian Johansen (christian@cjohansen.no)
6228 * Copyright (c) 2010-2013 Christian Johansen
6230 (function (sinonGlobal
, global
) {
6232 var slice
= Array
.prototype.slice
;
6234 function makeApi(sinon
) {
6237 function verifyIsStub() {
6240 for (var i
= 0, l
= arguments
.length
; i
< l
; ++i
) {
6241 method
= arguments
[i
];
6244 assert
.fail("fake is not a spy");
6247 if (method
.proxy
&& method
.proxy
.isSinonProxy
) {
6248 verifyIsStub(method
.proxy
);
6250 if (typeof method
!== "function") {
6251 assert
.fail(method
+ " is not a function");
6254 if (typeof method
.getCall
!== "function") {
6255 assert
.fail(method
+ " is not stubbed");
6262 function verifyIsValidAssertion(assertionMethod
, assertionArgs
) {
6263 switch (assertionMethod
) {
6268 case "calledThrice":
6269 if (assertionArgs
.length
!== 0) {
6270 assert
.fail(assertionMethod
+
6271 " takes 1 argument but was called with " +
6272 (assertionArgs
.length
+ 1) + " arguments");
6280 function failAssertion(object
, msg
) {
6281 object
= object
|| global
;
6282 var failMethod
= object
.fail
|| assert
.fail
;
6283 failMethod
.call(object
, msg
);
6286 function mirrorPropAsAssertion(name
, method
, message
) {
6287 if (arguments
.length
=== 2) {
6292 assert
[name
] = function (fake
) {
6295 var args
= slice
.call(arguments
, 1);
6296 verifyIsValidAssertion(name
, args
);
6300 if (typeof method
=== "function") {
6301 failed
= !method(fake
);
6303 failed
= typeof fake
[method
] === "function" ?
6304 !fake
[method
].apply(fake
, args
) : !fake
[method
];
6308 failAssertion(this, (fake
.printf
|| fake
.proxy
.printf
).apply(fake
, [message
].concat(args
)));
6315 function exposedName(prefix
, prop
) {
6316 return !prefix
|| /^fail/.test(prop
) ? prop
:
6317 prefix
+ prop
.slice(0, 1).toUpperCase() + prop
.slice(1);
6321 failException
: "AssertError",
6323 fail
: function fail(message
) {
6324 var error
= new Error(message
);
6325 error
.name
= this.failException
|| assert
.failException
;
6330 pass
: function pass() {},
6332 callOrder
: function assertCallOrder() {
6333 verifyIsStub
.apply(null, arguments
);
6337 if (!sinon
.calledInOrder(arguments
)) {
6339 expected
= [].join
.call(arguments
, ", ");
6340 var calls
= slice
.call(arguments
);
6341 var i
= calls
.length
;
6343 if (!calls
[--i
].called
) {
6347 actual
= sinon
.orderByFirstCall(calls
).join(", ");
6349 // If this fails, we'll just fall back to the blank string
6352 failAssertion(this, "expected " + expected
+ " to be " +
6353 "called in order but were called as " + actual
);
6355 assert
.pass("callOrder");
6359 callCount
: function assertCallCount(method
, count
) {
6360 verifyIsStub(method
);
6362 if (method
.callCount
!== count
) {
6363 var msg
= "expected %n to be called " + sinon
.timesInWords(count
) +
6364 " but was called %c%C";
6365 failAssertion(this, method
.printf(msg
));
6367 assert
.pass("callCount");
6371 expose
: function expose(target
, options
) {
6373 throw new TypeError("target is null or undefined");
6376 var o
= options
|| {};
6377 var prefix
= typeof o
.prefix
=== "undefined" && "assert" || o
.prefix
;
6378 var includeFail
= typeof o
.includeFail
=== "undefined" || !!o
.includeFail
;
6380 for (var method
in this) {
6381 if (method
!== "expose" && (includeFail
|| !/^(fail)/.test(method
))) {
6382 target
[exposedName(prefix
, method
)] = this[method
];
6389 match
: function match(actual
, expectation
) {
6390 var matcher
= sinon
.match(expectation
);
6391 if (matcher
.test(actual
)) {
6392 assert
.pass("match");
6395 "expected value to match",
6396 " expected = " + sinon
.format(expectation
),
6397 " actual = " + sinon
.format(actual
)
6400 failAssertion(this, formatted
.join("\n"));
6405 mirrorPropAsAssertion("called", "expected %n to have been called at least once but was never called");
6406 mirrorPropAsAssertion("notCalled", function (spy
) {
6408 }, "expected %n to not have been called but was called %c%C");
6409 mirrorPropAsAssertion("calledOnce", "expected %n to be called once but was called %c%C");
6410 mirrorPropAsAssertion("calledTwice", "expected %n to be called twice but was called %c%C");
6411 mirrorPropAsAssertion("calledThrice", "expected %n to be called thrice but was called %c%C");
6412 mirrorPropAsAssertion("calledOn", "expected %n to be called with %1 as this but was called with %t");
6413 mirrorPropAsAssertion(
6415 "expected %n to always be called with %1 as this but was called with %t"
6417 mirrorPropAsAssertion("calledWithNew", "expected %n to be called with new");
6418 mirrorPropAsAssertion("alwaysCalledWithNew", "expected %n to always be called with new");
6419 mirrorPropAsAssertion("calledWith", "expected %n to be called with arguments %*%C");
6420 mirrorPropAsAssertion("calledWithMatch", "expected %n to be called with match %*%C");
6421 mirrorPropAsAssertion("alwaysCalledWith", "expected %n to always be called with arguments %*%C");
6422 mirrorPropAsAssertion("alwaysCalledWithMatch", "expected %n to always be called with match %*%C");
6423 mirrorPropAsAssertion("calledWithExactly", "expected %n to be called with exact arguments %*%C");
6424 mirrorPropAsAssertion("alwaysCalledWithExactly", "expected %n to always be called with exact arguments %*%C");
6425 mirrorPropAsAssertion("neverCalledWith", "expected %n to never be called with arguments %*%C");
6426 mirrorPropAsAssertion("neverCalledWithMatch", "expected %n to never be called with match %*%C");
6427 mirrorPropAsAssertion("threw", "%n did not throw exception%C");
6428 mirrorPropAsAssertion("alwaysThrew", "%n did not always throw exception%C");
6430 sinon
.assert
= assert
;
6434 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
6435 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
6437 function loadDependencies(require
, exports
, module
) {
6438 var sinon
= require("./util/core");
6440 require("./format");
6441 module
.exports
= makeApi(sinon
);
6445 define(loadDependencies
);
6450 loadDependencies(require
, module
.exports
, module
);
6455 makeApi(sinonGlobal
);
6458 typeof sinon
=== "object" && sinon
, // eslint-disable-line no-undef
6459 typeof global
!== "undefined" ? global
: self