2 * Sinon.JS 1.17.3, 2016/01/27
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, 'm:s' and 'h:m:s'. Each part must be two digits");
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 firstTimer(clock
) {
908 var timers
= clock
.timers
,
913 if (timers
.hasOwnProperty(id
)) {
914 if (!timer
|| compareTimers(timer
, timers
[id
]) === 1) {
923 function callTimer(clock
, timer
) {
926 if (typeof timer
.interval
=== "number") {
927 clock
.timers
[timer
.id
].callAt
+= timer
.interval
;
929 delete clock
.timers
[timer
.id
];
933 if (typeof timer
.func
=== "function") {
934 timer
.func
.apply(null, timer
.args
);
942 if (!clock
.timers
[timer
.id
]) {
954 function timerType(timer
) {
955 if (timer
.immediate
) {
957 } else if (typeof timer
.interval
!== "undefined") {
964 function clearTimer(clock
, timerId
, ttype
) {
966 // null appears to be allowed in most browsers, and appears to be
967 // relied upon by some libraries, like Bootstrap carousel
975 // in Node, timerId is an object with .ref()/.unref(), and
976 // its .id field is the actual timer id.
977 if (typeof timerId
=== "object") {
978 timerId
= timerId
.id
;
981 if (clock
.timers
.hasOwnProperty(timerId
)) {
982 // check that the ID matches a timer of the correct type
983 var timer
= clock
.timers
[timerId
];
984 if (timerType(timer
) === ttype
) {
985 delete clock
.timers
[timerId
];
987 throw new Error("Cannot clear timer: timer created with set" + ttype
+ "() but cleared with clear" + timerType(timer
) + "()");
992 function uninstall(clock
, target
) {
997 for (i
= 0, l
= clock
.methods
.length
; i
< l
; i
++) {
998 method
= clock
.methods
[i
];
1000 if (target
[method
].hadOwnProperty
) {
1001 target
[method
] = clock
["_" + method
];
1004 delete target
[method
];
1009 // Prevent multiple executions which will completely remove these props
1013 function hijackMethod(target
, method
, clock
) {
1016 clock
[method
].hadOwnProperty
= Object
.prototype.hasOwnProperty
.call(target
, method
);
1017 clock
["_" + method
] = target
[method
];
1019 if (method
=== "Date") {
1020 var date
= mirrorDateProperties(clock
[method
], target
[method
]);
1021 target
[method
] = date
;
1023 target
[method
] = function () {
1024 return clock
[method
].apply(clock
, arguments
);
1027 for (prop
in clock
[method
]) {
1028 if (clock
[method
].hasOwnProperty(prop
)) {
1029 target
[method
][prop
] = clock
[method
][prop
];
1034 target
[method
].clock
= clock
;
1038 setTimeout
: setTimeout
,
1039 clearTimeout
: clearTimeout
,
1040 setImmediate
: global
.setImmediate
,
1041 clearImmediate
: global
.clearImmediate
,
1042 setInterval
: setInterval
,
1043 clearInterval
: clearInterval
,
1047 var keys
= Object
.keys
|| function (obj
) {
1052 if (obj
.hasOwnProperty(key
)) {
1060 exports
.timers
= timers
;
1062 function createClock(now
) {
1069 clock
.Date
.clock
= clock
;
1071 clock
.setTimeout
= function setTimeout(func
, timeout
) {
1072 return addTimer(clock
, {
1074 args
: Array
.prototype.slice
.call(arguments
, 2),
1079 clock
.clearTimeout
= function clearTimeout(timerId
) {
1080 return clearTimer(clock
, timerId
, "Timeout");
1083 clock
.setInterval
= function setInterval(func
, timeout
) {
1084 return addTimer(clock
, {
1086 args
: Array
.prototype.slice
.call(arguments
, 2),
1092 clock
.clearInterval
= function clearInterval(timerId
) {
1093 return clearTimer(clock
, timerId
, "Interval");
1096 clock
.setImmediate
= function setImmediate(func
) {
1097 return addTimer(clock
, {
1099 args
: Array
.prototype.slice
.call(arguments
, 1),
1104 clock
.clearImmediate
= function clearImmediate(timerId
) {
1105 return clearTimer(clock
, timerId
, "Immediate");
1108 clock
.tick
= function tick(ms
) {
1109 ms
= typeof ms
=== "number" ? ms
: parseTime(ms
);
1110 var tickFrom
= clock
.now
, tickTo
= clock
.now
+ ms
, previous
= clock
.now
;
1111 var timer
= firstTimerInRange(clock
, tickFrom
, tickTo
);
1114 clock
.duringTick
= true;
1117 while (timer
&& tickFrom
<= tickTo
) {
1118 if (clock
.timers
[timer
.id
]) {
1119 tickFrom
= clock
.now
= timer
.callAt
;
1122 callTimer(clock
, timer
);
1123 // compensate for any setSystemTime() call during timer callback
1124 if (oldNow
!== clock
.now
) {
1125 tickFrom
+= clock
.now
- oldNow
;
1126 tickTo
+= clock
.now
- oldNow
;
1127 previous
+= clock
.now
- oldNow
;
1130 firstException
= firstException
|| e
;
1134 timer
= firstTimerInRange(clock
, previous
, tickTo
);
1135 previous
= tickFrom
;
1138 clock
.duringTick
= false;
1141 if (firstException
) {
1142 throw firstException
;
1148 clock
.next
= function next() {
1149 var timer
= firstTimer(clock
);
1154 clock
.duringTick
= true;
1156 clock
.now
= timer
.callAt
;
1157 callTimer(clock
, timer
);
1160 clock
.duringTick
= false;
1164 clock
.reset
= function reset() {
1168 clock
.setSystemTime
= function setSystemTime(now
) {
1169 // determine time difference
1170 var newNow
= getEpoch(now
);
1171 var difference
= newNow
- clock
.now
;
1173 // update 'system clock'
1176 // update timers and intervals to keep them stable
1177 for (var id
in clock
.timers
) {
1178 if (clock
.timers
.hasOwnProperty(id
)) {
1179 var timer
= clock
.timers
[id
];
1180 timer
.createdAt
+= difference
;
1181 timer
.callAt
+= difference
;
1188 exports
.createClock
= createClock
;
1190 exports
.install
= function install(target
, now
, toFake
) {
1194 if (typeof target
=== "number") {
1204 var clock
= createClock(now
);
1206 clock
.uninstall = function () {
1207 uninstall(clock
, target
);
1210 clock
.methods
= toFake
|| [];
1212 if (clock
.methods
.length
=== 0) {
1213 clock
.methods
= keys(timers
);
1216 for (i
= 0, l
= clock
.methods
.length
; i
< l
; i
++) {
1217 hijackMethod(target
, clock
.methods
[i
], clock
);
1225 }).call(this,typeof global
!== "undefined" ? global
: typeof self
!== "undefined" ? self
: typeof window
!== "undefined" ? window
: {})
1231 * Sinon core utilities. For internal use only.
1233 * @author Christian Johansen (christian@cjohansen.no)
1236 * Copyright (c) 2010-2013 Christian Johansen
1238 var sinon
= (function () {
1240 // eslint-disable-line no-unused-vars
1243 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
1244 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
1246 function loadDependencies(require
, exports
, module
) {
1247 sinonModule
= module
.exports
= require("./sinon/util/core");
1248 require("./sinon/extend");
1249 require("./sinon/walk");
1250 require("./sinon/typeOf");
1251 require("./sinon/times_in_words");
1252 require("./sinon/spy");
1253 require("./sinon/call");
1254 require("./sinon/behavior");
1255 require("./sinon/stub");
1256 require("./sinon/mock");
1257 require("./sinon/collection");
1258 require("./sinon/assert");
1259 require("./sinon/sandbox");
1260 require("./sinon/test");
1261 require("./sinon/test_case");
1262 require("./sinon/match");
1263 require("./sinon/format");
1264 require("./sinon/log_error");
1268 define(loadDependencies
);
1269 } else if (isNode
) {
1270 loadDependencies(require
, module
.exports
, module
);
1271 sinonModule
= module
.exports
;
1280 * @depend ../../sinon.js
1283 * Sinon core utilities. For internal use only.
1285 * @author Christian Johansen (christian@cjohansen.no)
1288 * Copyright (c) 2010-2013 Christian Johansen
1290 (function (sinonGlobal
) {
1292 var div
= typeof document
!== "undefined" && document
.createElement("div");
1293 var hasOwn
= Object
.prototype.hasOwnProperty
;
1295 function isDOMNode(obj
) {
1296 var success
= false;
1299 obj
.appendChild(div
);
1300 success
= div
.parentNode
=== obj
;
1305 obj
.removeChild(div
);
1307 // Remove failed, not much we can do about that
1314 function isElement(obj
) {
1315 return div
&& obj
&& obj
.nodeType
=== 1 && isDOMNode(obj
);
1318 function isFunction(obj
) {
1319 return typeof obj
=== "function" || !!(obj
&& obj
.constructor && obj
.call
&& obj
.apply
);
1322 function isReallyNaN(val
) {
1323 return typeof val
=== "number" && isNaN(val
);
1326 function mirrorProperties(target
, source
) {
1327 for (var prop
in source
) {
1328 if (!hasOwn
.call(target
, prop
)) {
1329 target
[prop
] = source
[prop
];
1334 function isRestorable(obj
) {
1335 return typeof obj
=== "function" && typeof obj
.restore
=== "function" && obj
.restore
.sinon
;
1338 // Cheap way to detect if we have ES5 support.
1339 var hasES5Support
= "keys" in Object
;
1341 function makeApi(sinon
) {
1342 sinon
.wrapMethod
= function wrapMethod(object
, property
, method
) {
1344 throw new TypeError("Should wrap property of object");
1347 if (typeof method
!== "function" && typeof method
!== "object") {
1348 throw new TypeError("Method wrapper should be a function or a property descriptor");
1351 function checkWrappedMethod(wrappedMethod
) {
1354 if (!isFunction(wrappedMethod
)) {
1355 error
= new TypeError("Attempted to wrap " + (typeof wrappedMethod
) + " property " +
1356 property
+ " as function");
1357 } else if (wrappedMethod
.restore
&& wrappedMethod
.restore
.sinon
) {
1358 error
= new TypeError("Attempted to wrap " + property
+ " which is already wrapped");
1359 } else if (wrappedMethod
.calledBefore
) {
1360 var verb
= wrappedMethod
.returns
? "stubbed" : "spied on";
1361 error
= new TypeError("Attempted to wrap " + property
+ " which is already " + verb
);
1365 if (wrappedMethod
&& wrappedMethod
.stackTrace
) {
1366 error
.stack
+= "\n--------------\n" + wrappedMethod
.stackTrace
;
1372 var error
, wrappedMethod
, i
;
1374 // IE 8 does not support hasOwnProperty on the window object and Firefox has a problem
1375 // when using hasOwn.call on objects from other frames.
1376 var owned
= object
.hasOwnProperty
? object
.hasOwnProperty(property
) : hasOwn
.call(object
, property
);
1378 if (hasES5Support
) {
1379 var methodDesc
= (typeof method
=== "function") ? {value
: method
} : method
;
1380 var wrappedMethodDesc
= sinon
.getPropertyDescriptor(object
, property
);
1382 if (!wrappedMethodDesc
) {
1383 error
= new TypeError("Attempted to wrap " + (typeof wrappedMethod
) + " property " +
1384 property
+ " as function");
1385 } else if (wrappedMethodDesc
.restore
&& wrappedMethodDesc
.restore
.sinon
) {
1386 error
= new TypeError("Attempted to wrap " + property
+ " which is already wrapped");
1389 if (wrappedMethodDesc
&& wrappedMethodDesc
.stackTrace
) {
1390 error
.stack
+= "\n--------------\n" + wrappedMethodDesc
.stackTrace
;
1395 var types
= sinon
.objectKeys(methodDesc
);
1396 for (i
= 0; i
< types
.length
; i
++) {
1397 wrappedMethod
= wrappedMethodDesc
[types
[i
]];
1398 checkWrappedMethod(wrappedMethod
);
1401 mirrorProperties(methodDesc
, wrappedMethodDesc
);
1402 for (i
= 0; i
< types
.length
; i
++) {
1403 mirrorProperties(methodDesc
[types
[i
]], wrappedMethodDesc
[types
[i
]]);
1405 Object
.defineProperty(object
, property
, methodDesc
);
1407 wrappedMethod
= object
[property
];
1408 checkWrappedMethod(wrappedMethod
);
1409 object
[property
] = method
;
1410 method
.displayName
= property
;
1413 method
.displayName
= property
;
1415 // Set up a stack trace which can be used later to find what line of
1416 // code the original method was created on.
1417 method
.stackTrace
= (new Error("Stack Trace for original")).stack
;
1419 method
.restore = function () {
1420 // For prototype properties try to reset by delete first.
1421 // If this fails (ex: localStorage on mobile safari) then force a reset
1422 // via direct assignment.
1424 // In some cases `delete` may throw an error
1426 delete object
[property
];
1427 } catch (e
) {} // eslint-disable-line no-empty
1428 // For native code functions `delete` fails without throwing an error
1429 // on Chrome < 43, PhantomJS, etc.
1430 } else if (hasES5Support
) {
1431 Object
.defineProperty(object
, property
, wrappedMethodDesc
);
1434 // Use strict equality comparison to check failures then force a reset
1435 // via direct assignment.
1436 if (object
[property
] === method
) {
1437 object
[property
] = wrappedMethod
;
1441 method
.restore
.sinon
= true;
1443 if (!hasES5Support
) {
1444 mirrorProperties(method
, wrappedMethod
);
1450 sinon
.create
= function create(proto
) {
1451 var F = function () {};
1452 F
.prototype = proto
;
1456 sinon
.deepEqual
= function deepEqual(a
, b
) {
1457 if (sinon
.match
&& sinon
.match
.isMatcher(a
)) {
1461 if (typeof a
!== "object" || typeof b
!== "object") {
1462 return isReallyNaN(a
) && isReallyNaN(b
) || a
=== b
;
1465 if (isElement(a
) || isElement(b
)) {
1473 if ((a
=== null && b
!== null) || (a
!== null && b
=== null)) {
1477 if (a
instanceof RegExp
&& b
instanceof RegExp
) {
1478 return (a
.source
=== b
.source
) && (a
.global
=== b
.global
) &&
1479 (a
.ignoreCase
=== b
.ignoreCase
) && (a
.multiline
=== b
.multiline
);
1482 var aString
= Object
.prototype.toString
.call(a
);
1483 if (aString
!== Object
.prototype.toString
.call(b
)) {
1487 if (aString
=== "[object Date]") {
1488 return a
.valueOf() === b
.valueOf();
1495 if (aString
=== "[object Array]" && a
.length
!== b
.length
) {
1500 if (a
.hasOwnProperty(prop
)) {
1507 if (!deepEqual(a
[prop
], b
[prop
])) {
1514 if (b
.hasOwnProperty(prop
)) {
1519 return aLength
=== bLength
;
1522 sinon
.functionName
= function functionName(func
) {
1523 var name
= func
.displayName
|| func
.name
;
1525 // Use function decomposition as a last resort to get function
1526 // name. Does not rely on function decomposition to work - if it
1527 // doesn't debugging will be slightly less informative
1528 // (i.e. toString will say 'spy' rather than 'myFunc').
1530 var matches
= func
.toString().match(/function ([^\s\(]+)/);
1531 name
= matches
&& matches
[1];
1537 sinon
.functionToString
= function toString() {
1538 if (this.getCall
&& this.callCount
) {
1541 var i
= this.callCount
;
1544 thisValue
= this.getCall(i
).thisValue
;
1546 for (prop
in thisValue
) {
1547 if (thisValue
[prop
] === this) {
1554 return this.displayName
|| "sinon fake";
1557 sinon
.objectKeys
= function objectKeys(obj
) {
1558 if (obj
!== Object(obj
)) {
1559 throw new TypeError("sinon.objectKeys called on a non-object");
1565 if (hasOwn
.call(obj
, key
)) {
1573 sinon
.getPropertyDescriptor
= function getPropertyDescriptor(object
, property
) {
1577 while (proto
&& !(descriptor
= Object
.getOwnPropertyDescriptor(proto
, property
))) {
1578 proto
= Object
.getPrototypeOf(proto
);
1583 sinon
.getConfig = function (custom
) {
1585 custom
= custom
|| {};
1586 var defaults
= sinon
.defaultConfig
;
1588 for (var prop
in defaults
) {
1589 if (defaults
.hasOwnProperty(prop
)) {
1590 config
[prop
] = custom
.hasOwnProperty(prop
) ? custom
[prop
] : defaults
[prop
];
1597 sinon
.defaultConfig
= {
1598 injectIntoThis
: true,
1600 properties
: ["spy", "stub", "mock", "clock", "server", "requests"],
1601 useFakeTimers
: true,
1605 sinon
.timesInWords
= function timesInWords(count
) {
1606 return count
=== 1 && "once" ||
1607 count
=== 2 && "twice" ||
1608 count
=== 3 && "thrice" ||
1609 (count
|| 0) + " times";
1612 sinon
.calledInOrder = function (spies
) {
1613 for (var i
= 1, l
= spies
.length
; i
< l
; i
++) {
1614 if (!spies
[i
- 1].calledBefore(spies
[i
]) || !spies
[i
].called
) {
1622 sinon
.orderByFirstCall = function (spies
) {
1623 return spies
.sort(function (a
, b
) {
1624 // uuid, won't ever be equal
1625 var aCall
= a
.getCall(0);
1626 var bCall
= b
.getCall(0);
1627 var aId
= aCall
&& aCall
.callId
|| -1;
1628 var bId
= bCall
&& bCall
.callId
|| -1;
1630 return aId
< bId
? -1 : 1;
1634 sinon
.createStubInstance = function (constructor) {
1635 if (typeof constructor !== "function") {
1636 throw new TypeError("The constructor should be a function.");
1638 return sinon
.stub(sinon
.create(constructor.prototype));
1641 sinon
.restore = function (object
) {
1642 if (object
!== null && typeof object
=== "object") {
1643 for (var prop
in object
) {
1644 if (isRestorable(object
[prop
])) {
1645 object
[prop
].restore();
1648 } else if (isRestorable(object
)) {
1656 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
1657 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
1659 function loadDependencies(require
, exports
) {
1664 define(loadDependencies
);
1669 loadDependencies(require
, module
.exports
, module
);
1674 makeApi(sinonGlobal
);
1677 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
1681 * @depend util/core.js
1683 (function (sinonGlobal
) {
1685 function makeApi(sinon
) {
1687 // Adapted from https://developer.mozilla.org/en/docs/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug
1688 var hasDontEnumBug
= (function () {
1690 constructor: function () {
1693 toString: function () {
1696 valueOf: function () {
1699 toLocaleString: function () {
1702 prototype: function () {
1705 isPrototypeOf: function () {
1708 propertyIsEnumerable: function () {
1711 hasOwnProperty: function () {
1714 length: function () {
1717 unique: function () {
1723 for (var prop
in obj
) {
1724 if (obj
.hasOwnProperty(prop
)) {
1725 result
.push(obj
[prop
]());
1728 return result
.join("") !== "0123456789";
1731 /* Public: Extend target in place with all (own) properties from sources in-order. Thus, last source will
1732 * override properties in previous sources.
1734 * target - The Object to extend
1735 * sources - Objects to copy properties from.
1737 * Returns the extended target
1739 function extend(target
/*, sources */) {
1740 var sources
= Array
.prototype.slice
.call(arguments
, 1);
1741 var source
, i
, prop
;
1743 for (i
= 0; i
< sources
.length
; i
++) {
1744 source
= sources
[i
];
1746 for (prop
in source
) {
1747 if (source
.hasOwnProperty(prop
)) {
1748 target
[prop
] = source
[prop
];
1752 // Make sure we copy (own) toString method even when in JScript with DontEnum bug
1753 // See https://developer.mozilla.org/en/docs/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug
1754 if (hasDontEnumBug
&& source
.hasOwnProperty("toString") && source
.toString
!== target
.toString
) {
1755 target
.toString
= source
.toString
;
1762 sinon
.extend
= extend
;
1763 return sinon
.extend
;
1766 function loadDependencies(require
, exports
, module
) {
1767 var sinon
= require("./util/core");
1768 module
.exports
= makeApi(sinon
);
1771 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
1772 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
1775 define(loadDependencies
);
1780 loadDependencies(require
, module
.exports
, module
);
1785 makeApi(sinonGlobal
);
1788 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
1792 * @depend util/core.js
1794 (function (sinonGlobal
) {
1796 function makeApi(sinon
) {
1798 function timesInWords(count
) {
1807 return (count
|| 0) + " times";
1811 sinon
.timesInWords
= timesInWords
;
1812 return sinon
.timesInWords
;
1815 function loadDependencies(require
, exports
, module
) {
1816 var core
= require("./util/core");
1817 module
.exports
= makeApi(core
);
1820 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
1821 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
1824 define(loadDependencies
);
1829 loadDependencies(require
, module
.exports
, module
);
1834 makeApi(sinonGlobal
);
1837 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
1841 * @depend util/core.js
1846 * @author Christian Johansen (christian@cjohansen.no)
1849 * Copyright (c) 2010-2014 Christian Johansen
1851 (function (sinonGlobal
) {
1853 function makeApi(sinon
) {
1854 function typeOf(value
) {
1855 if (value
=== null) {
1857 } else if (value
=== undefined) {
1860 var string
= Object
.prototype.toString
.call(value
);
1861 return string
.substring(8, string
.length
- 1).toLowerCase();
1864 sinon
.typeOf
= typeOf
;
1865 return sinon
.typeOf
;
1868 function loadDependencies(require
, exports
, module
) {
1869 var core
= require("./util/core");
1870 module
.exports
= makeApi(core
);
1873 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
1874 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
1877 define(loadDependencies
);
1882 loadDependencies(require
, module
.exports
, module
);
1887 makeApi(sinonGlobal
);
1890 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
1894 * @depend util/core.js
1897 /*jslint eqeqeq: false, onevar: false, plusplus: false*/
1898 /*global module, require, sinon*/
1902 * @author Maximilian Antoni (mail@maxantoni.de)
1905 * Copyright (c) 2012 Maximilian Antoni
1907 (function (sinonGlobal
) {
1909 function makeApi(sinon
) {
1910 function assertType(value
, type
, name
) {
1911 var actual
= sinon
.typeOf(value
);
1912 if (actual
!== type
) {
1913 throw new TypeError("Expected type of " + name
+ " to be " +
1914 type
+ ", but was " + actual
);
1919 toString: function () {
1920 return this.message
;
1924 function isMatcher(object
) {
1925 return matcher
.isPrototypeOf(object
);
1928 function matchObject(expectation
, actual
) {
1929 if (actual
=== null || actual
=== undefined) {
1932 for (var key
in expectation
) {
1933 if (expectation
.hasOwnProperty(key
)) {
1934 var exp
= expectation
[key
];
1935 var act
= actual
[key
];
1936 if (isMatcher(exp
)) {
1937 if (!exp
.test(act
)) {
1940 } else if (sinon
.typeOf(exp
) === "object") {
1941 if (!matchObject(exp
, act
)) {
1944 } else if (!sinon
.deepEqual(exp
, act
)) {
1952 function match(expectation
, message
) {
1953 var m
= sinon
.create(matcher
);
1954 var type
= sinon
.typeOf(expectation
);
1957 if (typeof expectation
.test
=== "function") {
1958 m
.test = function (actual
) {
1959 return expectation
.test(actual
) === true;
1961 m
.message
= "match(" + sinon
.functionName(expectation
.test
) + ")";
1965 for (var key
in expectation
) {
1966 if (expectation
.hasOwnProperty(key
)) {
1967 str
.push(key
+ ": " + expectation
[key
]);
1970 m
.test = function (actual
) {
1971 return matchObject(expectation
, actual
);
1973 m
.message
= "match(" + str
.join(", ") + ")";
1976 m
.test = function (actual
) {
1977 // we need type coercion here
1978 return expectation
== actual
; // eslint-disable-line eqeqeq
1982 m
.test = function (actual
) {
1983 if (typeof actual
!== "string") {
1986 return actual
.indexOf(expectation
) !== -1;
1988 m
.message
= "match(\"" + expectation
+ "\")";
1991 m
.test = function (actual
) {
1992 if (typeof actual
!== "string") {
1995 return expectation
.test(actual
);
1999 m
.test
= expectation
;
2001 m
.message
= message
;
2003 m
.message
= "match(" + sinon
.functionName(expectation
) + ")";
2007 m
.test = function (actual
) {
2008 return sinon
.deepEqual(expectation
, actual
);
2012 m
.message
= "match(" + expectation
+ ")";
2017 matcher
.or = function (m2
) {
2018 if (!arguments
.length
) {
2019 throw new TypeError("Matcher expected");
2020 } else if (!isMatcher(m2
)) {
2024 var or
= sinon
.create(matcher
);
2025 or
.test = function (actual
) {
2026 return m1
.test(actual
) || m2
.test(actual
);
2028 or
.message
= m1
.message
+ ".or(" + m2
.message
+ ")";
2032 matcher
.and = function (m2
) {
2033 if (!arguments
.length
) {
2034 throw new TypeError("Matcher expected");
2035 } else if (!isMatcher(m2
)) {
2039 var and
= sinon
.create(matcher
);
2040 and
.test = function (actual
) {
2041 return m1
.test(actual
) && m2
.test(actual
);
2043 and
.message
= m1
.message
+ ".and(" + m2
.message
+ ")";
2047 match
.isMatcher
= isMatcher
;
2049 match
.any
= match(function () {
2053 match
.defined
= match(function (actual
) {
2054 return actual
!== null && actual
!== undefined;
2057 match
.truthy
= match(function (actual
) {
2061 match
.falsy
= match(function (actual
) {
2065 match
.same = function (expectation
) {
2066 return match(function (actual
) {
2067 return expectation
=== actual
;
2068 }, "same(" + expectation
+ ")");
2071 match
.typeOf = function (type
) {
2072 assertType(type
, "string", "type");
2073 return match(function (actual
) {
2074 return sinon
.typeOf(actual
) === type
;
2075 }, "typeOf(\"" + type
+ "\")");
2078 match
.instanceOf = function (type
) {
2079 assertType(type
, "function", "type");
2080 return match(function (actual
) {
2081 return actual
instanceof type
;
2082 }, "instanceOf(" + sinon
.functionName(type
) + ")");
2085 function createPropertyMatcher(propertyTest
, messagePrefix
) {
2086 return function (property
, value
) {
2087 assertType(property
, "string", "property");
2088 var onlyProperty
= arguments
.length
=== 1;
2089 var message
= messagePrefix
+ "(\"" + property
+ "\"";
2090 if (!onlyProperty
) {
2091 message
+= ", " + value
;
2094 return match(function (actual
) {
2095 if (actual
=== undefined || actual
=== null ||
2096 !propertyTest(actual
, property
)) {
2099 return onlyProperty
|| sinon
.deepEqual(value
, actual
[property
]);
2104 match
.has
= createPropertyMatcher(function (actual
, property
) {
2105 if (typeof actual
=== "object") {
2106 return property
in actual
;
2108 return actual
[property
] !== undefined;
2111 match
.hasOwn
= createPropertyMatcher(function (actual
, property
) {
2112 return actual
.hasOwnProperty(property
);
2115 match
.bool
= match
.typeOf("boolean");
2116 match
.number
= match
.typeOf("number");
2117 match
.string
= match
.typeOf("string");
2118 match
.object
= match
.typeOf("object");
2119 match
.func
= match
.typeOf("function");
2120 match
.array
= match
.typeOf("array");
2121 match
.regexp
= match
.typeOf("regexp");
2122 match
.date
= match
.typeOf("date");
2124 sinon
.match
= match
;
2128 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
2129 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
2131 function loadDependencies(require
, exports
, module
) {
2132 var sinon
= require("./util/core");
2133 require("./typeOf");
2134 module
.exports
= makeApi(sinon
);
2138 define(loadDependencies
);
2143 loadDependencies(require
, module
.exports
, module
);
2148 makeApi(sinonGlobal
);
2151 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
2155 * @depend util/core.js
2160 * @author Christian Johansen (christian@cjohansen.no)
2163 * Copyright (c) 2010-2014 Christian Johansen
2165 (function (sinonGlobal
, formatio
) {
2167 function makeApi(sinon
) {
2168 function valueFormatter(value
) {
2172 function getFormatioFormatter() {
2173 var formatter
= formatio
.configure({
2174 quoteStrings
: false,
2175 limitChildrenCount
: 250
2179 return formatter
.ascii
.apply(formatter
, arguments
);
2185 function getNodeFormatter() {
2187 var util
= require("util");
2189 /* Node, but no util module - would be very old, but better safe than sorry */
2192 function format(v
) {
2193 var isObjectWithNativeToString
= typeof v
=== "object" && v
.toString
=== Object
.prototype.toString
;
2194 return isObjectWithNativeToString
? util
.inspect(v
) : v
;
2197 return util
? format
: valueFormatter
;
2200 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
2205 formatio
= require("formatio");
2207 catch (e
) {} // eslint-disable-line no-empty
2211 formatter
= getFormatioFormatter();
2212 } else if (isNode
) {
2213 formatter
= getNodeFormatter();
2215 formatter
= valueFormatter
;
2218 sinon
.format
= formatter
;
2219 return sinon
.format
;
2222 function loadDependencies(require
, exports
, module
) {
2223 var sinon
= require("./util/core");
2224 module
.exports
= makeApi(sinon
);
2227 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
2228 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
2231 define(loadDependencies
);
2236 loadDependencies(require
, module
.exports
, module
);
2241 makeApi(sinonGlobal
);
2244 typeof sinon
=== "object" && sinon
, // eslint-disable-line no-undef
2245 typeof formatio
=== "object" && formatio
// eslint-disable-line no-undef
2249 * @depend util/core.js
2256 * @author Christian Johansen (christian@cjohansen.no)
2257 * @author Maximilian Antoni (mail@maxantoni.de)
2260 * Copyright (c) 2010-2013 Christian Johansen
2261 * Copyright (c) 2013 Maximilian Antoni
2263 (function (sinonGlobal
) {
2265 var slice
= Array
.prototype.slice
;
2267 function makeApi(sinon
) {
2268 function throwYieldError(proxy
, text
, args
) {
2269 var msg
= sinon
.functionName(proxy
) + text
;
2271 msg
+= " Received [" + slice
.call(args
).join(", ") + "]";
2273 throw new Error(msg
);
2277 calledOn
: function calledOn(thisValue
) {
2278 if (sinon
.match
&& sinon
.match
.isMatcher(thisValue
)) {
2279 return thisValue
.test(this.thisValue
);
2281 return this.thisValue
=== thisValue
;
2284 calledWith
: function calledWith() {
2285 var l
= arguments
.length
;
2286 if (l
> this.args
.length
) {
2289 for (var i
= 0; i
< l
; i
+= 1) {
2290 if (!sinon
.deepEqual(arguments
[i
], this.args
[i
])) {
2298 calledWithMatch
: function calledWithMatch() {
2299 var l
= arguments
.length
;
2300 if (l
> this.args
.length
) {
2303 for (var i
= 0; i
< l
; i
+= 1) {
2304 var actual
= this.args
[i
];
2305 var expectation
= arguments
[i
];
2306 if (!sinon
.match
|| !sinon
.match(expectation
).test(actual
)) {
2313 calledWithExactly
: function calledWithExactly() {
2314 return arguments
.length
=== this.args
.length
&&
2315 this.calledWith
.apply(this, arguments
);
2318 notCalledWith
: function notCalledWith() {
2319 return !this.calledWith
.apply(this, arguments
);
2322 notCalledWithMatch
: function notCalledWithMatch() {
2323 return !this.calledWithMatch
.apply(this, arguments
);
2326 returned
: function returned(value
) {
2327 return sinon
.deepEqual(value
, this.returnValue
);
2330 threw
: function threw(error
) {
2331 if (typeof error
=== "undefined" || !this.exception
) {
2332 return !!this.exception
;
2335 return this.exception
=== error
|| this.exception
.name
=== error
;
2338 calledWithNew
: function calledWithNew() {
2339 return this.proxy
.prototype && this.thisValue
instanceof this.proxy
;
2342 calledBefore: function (other
) {
2343 return this.callId
< other
.callId
;
2346 calledAfter: function (other
) {
2347 return this.callId
> other
.callId
;
2350 callArg: function (pos
) {
2354 callArgOn: function (pos
, thisValue
) {
2355 this.args
[pos
].apply(thisValue
);
2358 callArgWith: function (pos
) {
2359 this.callArgOnWith
.apply(this, [pos
, null].concat(slice
.call(arguments
, 1)));
2362 callArgOnWith: function (pos
, thisValue
) {
2363 var args
= slice
.call(arguments
, 2);
2364 this.args
[pos
].apply(thisValue
, args
);
2367 "yield": function () {
2368 this.yieldOn
.apply(this, [null].concat(slice
.call(arguments
, 0)));
2371 yieldOn: function (thisValue
) {
2372 var args
= this.args
;
2373 for (var i
= 0, l
= args
.length
; i
< l
; ++i
) {
2374 if (typeof args
[i
] === "function") {
2375 args
[i
].apply(thisValue
, slice
.call(arguments
, 1));
2379 throwYieldError(this.proxy
, " cannot yield since no callback was passed.", args
);
2382 yieldTo: function (prop
) {
2383 this.yieldToOn
.apply(this, [prop
, null].concat(slice
.call(arguments
, 1)));
2386 yieldToOn: function (prop
, thisValue
) {
2387 var args
= this.args
;
2388 for (var i
= 0, l
= args
.length
; i
< l
; ++i
) {
2389 if (args
[i
] && typeof args
[i
][prop
] === "function") {
2390 args
[i
][prop
].apply(thisValue
, slice
.call(arguments
, 2));
2394 throwYieldError(this.proxy
, " cannot yield to '" + prop
+
2395 "' since no callback was passed.", args
);
2398 getStackFrames: function () {
2399 // Omit the error message and the two top stack frames in sinon itself:
2400 return this.stack
&& this.stack
.split("\n").slice(3);
2403 toString: function () {
2404 var callStr
= this.proxy
? this.proxy
.toString() + "(" : "";
2411 for (var i
= 0, l
= this.args
.length
; i
< l
; ++i
) {
2412 args
.push(sinon
.format(this.args
[i
]));
2415 callStr
= callStr
+ args
.join(", ") + ")";
2417 if (typeof this.returnValue
!== "undefined") {
2418 callStr
+= " => " + sinon
.format(this.returnValue
);
2421 if (this.exception
) {
2422 callStr
+= " !" + this.exception
.name
;
2424 if (this.exception
.message
) {
2425 callStr
+= "(" + this.exception
.message
+ ")";
2429 callStr
+= this.getStackFrames()[0].replace(/^\s*(?:at\s+|@)?/, " at ");
2437 callProto
.invokeCallback
= callProto
.yield;
2439 function createSpyCall(spy
, thisValue
, args
, returnValue
, exception
, id
, stack
) {
2440 if (typeof id
!== "number") {
2441 throw new TypeError("Call id is not a number");
2443 var proxyCall
= sinon
.create(callProto
);
2444 proxyCall
.proxy
= spy
;
2445 proxyCall
.thisValue
= thisValue
;
2446 proxyCall
.args
= args
;
2447 proxyCall
.returnValue
= returnValue
;
2448 proxyCall
.exception
= exception
;
2449 proxyCall
.callId
= id
;
2450 proxyCall
.stack
= stack
;
2454 createSpyCall
.toString
= callProto
.toString
; // used by mocks
2456 sinon
.spyCall
= createSpyCall
;
2457 return createSpyCall
;
2460 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
2461 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
2463 function loadDependencies(require
, exports
, module
) {
2464 var sinon
= require("./util/core");
2466 require("./format");
2467 module
.exports
= makeApi(sinon
);
2471 define(loadDependencies
);
2476 loadDependencies(require
, module
.exports
, module
);
2481 makeApi(sinonGlobal
);
2484 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
2488 * @depend times_in_words.js
2489 * @depend util/core.js
2497 * @author Christian Johansen (christian@cjohansen.no)
2500 * Copyright (c) 2010-2013 Christian Johansen
2502 (function (sinonGlobal
) {
2504 function makeApi(sinon
) {
2505 var push
= Array
.prototype.push
;
2506 var slice
= Array
.prototype.slice
;
2509 function spy(object
, property
, types
) {
2510 if (!property
&& typeof object
=== "function") {
2511 return spy
.create(object
);
2514 if (!object
&& !property
) {
2515 return spy
.create(function () { });
2519 var methodDesc
= sinon
.getPropertyDescriptor(object
, property
);
2520 for (var i
= 0; i
< types
.length
; i
++) {
2521 methodDesc
[types
[i
]] = spy
.create(methodDesc
[types
[i
]]);
2523 return sinon
.wrapMethod(object
, property
, methodDesc
);
2526 return sinon
.wrapMethod(object
, property
, spy
.create(object
[property
]));
2529 function matchingFake(fakes
, args
, strict
) {
2534 for (var i
= 0, l
= fakes
.length
; i
< l
; i
++) {
2535 if (fakes
[i
].matches(args
, strict
)) {
2541 function incrementCallCount() {
2543 this.callCount
+= 1;
2544 this.notCalled
= false;
2545 this.calledOnce
= this.callCount
=== 1;
2546 this.calledTwice
= this.callCount
=== 2;
2547 this.calledThrice
= this.callCount
=== 3;
2550 function createCallProperties() {
2551 this.firstCall
= this.getCall(0);
2552 this.secondCall
= this.getCall(1);
2553 this.thirdCall
= this.getCall(2);
2554 this.lastCall
= this.getCall(this.callCount
- 1);
2557 var vars
= "a,b,c,d,e,f,g,h,i,j,k,l";
2558 function createProxy(func
, proxyLength
) {
2559 // Retain the function length:
2562 eval("p = (function proxy(" + vars
.substring(0, proxyLength
* 2 - 1) + // eslint-disable-line no-eval
2563 ") { return p.invoke(func, this, slice.call(arguments)); });");
2565 p
= function proxy() {
2566 return p
.invoke(func
, this, slice
.call(arguments
));
2569 p
.isSinonProxy
= true;
2577 reset: function () {
2578 if (this.invoking
) {
2579 var err
= new Error("Cannot reset Sinon function while invoking it. " +
2580 "Move the call to .reset outside of the callback.");
2581 err
.name
= "InvalidResetException";
2585 this.called
= false;
2586 this.notCalled
= true;
2587 this.calledOnce
= false;
2588 this.calledTwice
= false;
2589 this.calledThrice
= false;
2591 this.firstCall
= null;
2592 this.secondCall
= null;
2593 this.thirdCall
= null;
2594 this.lastCall
= null;
2596 this.returnValues
= [];
2597 this.thisValues
= [];
2598 this.exceptions
= [];
2602 for (var i
= 0; i
< this.fakes
.length
; i
++) {
2603 this.fakes
[i
].reset();
2610 create
: function create(func
, spyLength
) {
2613 if (typeof func
!== "function") {
2614 func = function () { };
2616 name
= sinon
.functionName(func
);
2620 spyLength
= func
.length
;
2623 var proxy
= createProxy(func
, spyLength
);
2625 sinon
.extend(proxy
, spy
);
2626 delete proxy
.create
;
2627 sinon
.extend(proxy
, func
);
2630 proxy
.prototype = func
.prototype;
2631 proxy
.displayName
= name
|| "spy";
2632 proxy
.toString
= sinon
.functionToString
;
2633 proxy
.instantiateFake
= sinon
.spy
.create
;
2634 proxy
.id
= "spy#" + uuid
++;
2639 invoke
: function invoke(func
, thisValue
, args
) {
2640 var matching
= matchingFake(this.fakes
, args
);
2641 var exception
, returnValue
;
2643 incrementCallCount
.call(this);
2644 push
.call(this.thisValues
, thisValue
);
2645 push
.call(this.args
, args
);
2646 push
.call(this.callIds
, callId
++);
2648 // Make call properties available from within the spied function:
2649 createCallProperties
.call(this);
2652 this.invoking
= true;
2655 returnValue
= matching
.invoke(func
, thisValue
, args
);
2657 returnValue
= (this.func
|| func
).apply(thisValue
, args
);
2660 var thisCall
= this.getCall(this.callCount
- 1);
2661 if (thisCall
.calledWithNew() && typeof returnValue
!== "object") {
2662 returnValue
= thisValue
;
2667 delete this.invoking
;
2670 push
.call(this.exceptions
, exception
);
2671 push
.call(this.returnValues
, returnValue
);
2672 push
.call(this.stacks
, new Error().stack
);
2674 // Make return value and exception available in the calls:
2675 createCallProperties
.call(this);
2677 if (exception
!== undefined) {
2684 named
: function named(name
) {
2685 this.displayName
= name
;
2689 getCall
: function getCall(i
) {
2690 if (i
< 0 || i
>= this.callCount
) {
2694 return sinon
.spyCall(this, this.thisValues
[i
], this.args
[i
],
2695 this.returnValues
[i
], this.exceptions
[i
],
2696 this.callIds
[i
], this.stacks
[i
]);
2699 getCalls: function () {
2703 for (i
= 0; i
< this.callCount
; i
++) {
2704 calls
.push(this.getCall(i
));
2710 calledBefore
: function calledBefore(spyFn
) {
2715 if (!spyFn
.called
) {
2719 return this.callIds
[0] < spyFn
.callIds
[spyFn
.callIds
.length
- 1];
2722 calledAfter
: function calledAfter(spyFn
) {
2723 if (!this.called
|| !spyFn
.called
) {
2727 return this.callIds
[this.callCount
- 1] > spyFn
.callIds
[spyFn
.callCount
- 1];
2730 withArgs: function () {
2731 var args
= slice
.call(arguments
);
2734 var match
= matchingFake(this.fakes
, args
, true);
2743 var original
= this;
2744 var fake
= this.instantiateFake();
2745 fake
.matchingAguments
= args
;
2747 push
.call(this.fakes
, fake
);
2749 fake
.withArgs = function () {
2750 return original
.withArgs
.apply(original
, arguments
);
2753 for (var i
= 0; i
< this.args
.length
; i
++) {
2754 if (fake
.matches(this.args
[i
])) {
2755 incrementCallCount
.call(fake
);
2756 push
.call(fake
.thisValues
, this.thisValues
[i
]);
2757 push
.call(fake
.args
, this.args
[i
]);
2758 push
.call(fake
.returnValues
, this.returnValues
[i
]);
2759 push
.call(fake
.exceptions
, this.exceptions
[i
]);
2760 push
.call(fake
.callIds
, this.callIds
[i
]);
2763 createCallProperties
.call(fake
);
2768 matches: function (args
, strict
) {
2769 var margs
= this.matchingAguments
;
2771 if (margs
.length
<= args
.length
&&
2772 sinon
.deepEqual(margs
, args
.slice(0, margs
.length
))) {
2773 return !strict
|| margs
.length
=== args
.length
;
2777 printf: function (format
) {
2778 var spyInstance
= this;
2779 var args
= slice
.call(arguments
, 1);
2782 return (format
|| "").replace(/%(.)/g, function (match
, specifyer
) {
2783 formatter
= spyApi
.formatters
[specifyer
];
2785 if (typeof formatter
=== "function") {
2786 return formatter
.call(null, spyInstance
, args
);
2787 } else if (!isNaN(parseInt(specifyer
, 10))) {
2788 return sinon
.format(args
[specifyer
- 1]);
2791 return "%" + specifyer
;
2796 function delegateToCalls(method
, matchAny
, actual
, notCalled
) {
2797 spyApi
[method
] = function () {
2800 return notCalled
.apply(this, arguments
);
2808 for (var i
= 0, l
= this.callCount
; i
< l
; i
+= 1) {
2809 currentCall
= this.getCall(i
);
2811 if (currentCall
[actual
|| method
].apply(currentCall
, arguments
)) {
2820 return matches
=== this.callCount
;
2824 delegateToCalls("calledOn", true);
2825 delegateToCalls("alwaysCalledOn", false, "calledOn");
2826 delegateToCalls("calledWith", true);
2827 delegateToCalls("calledWithMatch", true);
2828 delegateToCalls("alwaysCalledWith", false, "calledWith");
2829 delegateToCalls("alwaysCalledWithMatch", false, "calledWithMatch");
2830 delegateToCalls("calledWithExactly", true);
2831 delegateToCalls("alwaysCalledWithExactly", false, "calledWithExactly");
2832 delegateToCalls("neverCalledWith", false, "notCalledWith", function () {
2835 delegateToCalls("neverCalledWithMatch", false, "notCalledWithMatch", function () {
2838 delegateToCalls("threw", true);
2839 delegateToCalls("alwaysThrew", false, "threw");
2840 delegateToCalls("returned", true);
2841 delegateToCalls("alwaysReturned", false, "returned");
2842 delegateToCalls("calledWithNew", true);
2843 delegateToCalls("alwaysCalledWithNew", false, "calledWithNew");
2844 delegateToCalls("callArg", false, "callArgWith", function () {
2845 throw new Error(this.toString() + " cannot call arg since it was not yet invoked.");
2847 spyApi
.callArgWith
= spyApi
.callArg
;
2848 delegateToCalls("callArgOn", false, "callArgOnWith", function () {
2849 throw new Error(this.toString() + " cannot call arg since it was not yet invoked.");
2851 spyApi
.callArgOnWith
= spyApi
.callArgOn
;
2852 delegateToCalls("yield", false, "yield", function () {
2853 throw new Error(this.toString() + " cannot yield since it was not yet invoked.");
2855 // "invokeCallback" is an alias for "yield" since "yield" is invalid in strict mode.
2856 spyApi
.invokeCallback
= spyApi
.yield;
2857 delegateToCalls("yieldOn", false, "yieldOn", function () {
2858 throw new Error(this.toString() + " cannot yield since it was not yet invoked.");
2860 delegateToCalls("yieldTo", false, "yieldTo", function (property
) {
2861 throw new Error(this.toString() + " cannot yield to '" + property
+
2862 "' since it was not yet invoked.");
2864 delegateToCalls("yieldToOn", false, "yieldToOn", function (property
) {
2865 throw new Error(this.toString() + " cannot yield to '" + property
+
2866 "' since it was not yet invoked.");
2869 spyApi
.formatters
= {
2870 c: function (spyInstance
) {
2871 return sinon
.timesInWords(spyInstance
.callCount
);
2874 n: function (spyInstance
) {
2875 return spyInstance
.toString();
2878 C: function (spyInstance
) {
2881 for (var i
= 0, l
= spyInstance
.callCount
; i
< l
; ++i
) {
2882 var stringifiedCall
= " " + spyInstance
.getCall(i
).toString();
2883 if (/\n/.test(calls
[i
- 1])) {
2884 stringifiedCall
= "\n" + stringifiedCall
;
2886 push
.call(calls
, stringifiedCall
);
2889 return calls
.length
> 0 ? "\n" + calls
.join("\n") : "";
2892 t: function (spyInstance
) {
2895 for (var i
= 0, l
= spyInstance
.callCount
; i
< l
; ++i
) {
2896 push
.call(objects
, sinon
.format(spyInstance
.thisValues
[i
]));
2899 return objects
.join(", ");
2902 "*": function (spyInstance
, args
) {
2905 for (var i
= 0, l
= args
.length
; i
< l
; ++i
) {
2906 push
.call(formatted
, sinon
.format(args
[i
]));
2909 return formatted
.join(", ");
2913 sinon
.extend(spy
, spyApi
);
2915 spy
.spyCall
= sinon
.spyCall
;
2921 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
2922 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
2924 function loadDependencies(require
, exports
, module
) {
2925 var core
= require("./util/core");
2927 require("./extend");
2928 require("./times_in_words");
2929 require("./format");
2930 module
.exports
= makeApi(core
);
2934 define(loadDependencies
);
2939 loadDependencies(require
, module
.exports
, module
);
2944 makeApi(sinonGlobal
);
2947 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
2951 * @depend util/core.js
2957 * @author Christian Johansen (christian@cjohansen.no)
2958 * @author Tim Fischbach (mail@timfischbach.de)
2961 * Copyright (c) 2010-2013 Christian Johansen
2963 (function (sinonGlobal
) {
2965 var slice
= Array
.prototype.slice
;
2966 var join
= Array
.prototype.join
;
2967 var useLeftMostCallback
= -1;
2968 var useRightMostCallback
= -2;
2970 var nextTick
= (function () {
2971 if (typeof process
=== "object" && typeof process
.nextTick
=== "function") {
2972 return process
.nextTick
;
2975 if (typeof setImmediate
=== "function") {
2976 return setImmediate
;
2979 return function (callback
) {
2980 setTimeout(callback
, 0);
2984 function throwsException(error
, message
) {
2985 if (typeof error
=== "string") {
2986 this.exception
= new Error(message
|| "");
2987 this.exception
.name
= error
;
2988 } else if (!error
) {
2989 this.exception
= new Error("Error");
2991 this.exception
= error
;
2997 function getCallback(behavior
, args
) {
2998 var callArgAt
= behavior
.callArgAt
;
3000 if (callArgAt
>= 0) {
3001 return args
[callArgAt
];
3006 if (callArgAt
=== useLeftMostCallback
) {
3007 argumentList
= args
;
3010 if (callArgAt
=== useRightMostCallback
) {
3011 argumentList
= slice
.call(args
).reverse();
3014 var callArgProp
= behavior
.callArgProp
;
3016 for (var i
= 0, l
= argumentList
.length
; i
< l
; ++i
) {
3017 if (!callArgProp
&& typeof argumentList
[i
] === "function") {
3018 return argumentList
[i
];
3021 if (callArgProp
&& argumentList
[i
] &&
3022 typeof argumentList
[i
][callArgProp
] === "function") {
3023 return argumentList
[i
][callArgProp
];
3030 function makeApi(sinon
) {
3031 function getCallbackError(behavior
, func
, args
) {
3032 if (behavior
.callArgAt
< 0) {
3035 if (behavior
.callArgProp
) {
3036 msg
= sinon
.functionName(behavior
.stub
) +
3037 " expected to yield to '" + behavior
.callArgProp
+
3038 "', but no object with such a property was passed.";
3040 msg
= sinon
.functionName(behavior
.stub
) +
3041 " expected to yield, but no callback was passed.";
3044 if (args
.length
> 0) {
3045 msg
+= " Received [" + join
.call(args
, ", ") + "]";
3051 return "argument at index " + behavior
.callArgAt
+ " is not a function: " + func
;
3054 function callCallback(behavior
, args
) {
3055 if (typeof behavior
.callArgAt
=== "number") {
3056 var func
= getCallback(behavior
, args
);
3058 if (typeof func
!== "function") {
3059 throw new TypeError(getCallbackError(behavior
, func
, args
));
3062 if (behavior
.callbackAsync
) {
3063 nextTick(function () {
3064 func
.apply(behavior
.callbackContext
, behavior
.callbackArguments
);
3067 func
.apply(behavior
.callbackContext
, behavior
.callbackArguments
);
3073 create
: function create(stub
) {
3074 var behavior
= sinon
.extend({}, sinon
.behavior
);
3075 delete behavior
.create
;
3076 behavior
.stub
= stub
;
3081 isPresent
: function isPresent() {
3082 return (typeof this.callArgAt
=== "number" ||
3084 typeof this.returnArgAt
=== "number" ||
3086 this.returnValueDefined
);
3089 invoke
: function invoke(context
, args
) {
3090 callCallback(this, args
);
3092 if (this.exception
) {
3093 throw this.exception
;
3094 } else if (typeof this.returnArgAt
=== "number") {
3095 return args
[this.returnArgAt
];
3096 } else if (this.returnThis
) {
3100 return this.returnValue
;
3103 onCall
: function onCall(index
) {
3104 return this.stub
.onCall(index
);
3107 onFirstCall
: function onFirstCall() {
3108 return this.stub
.onFirstCall();
3111 onSecondCall
: function onSecondCall() {
3112 return this.stub
.onSecondCall();
3115 onThirdCall
: function onThirdCall() {
3116 return this.stub
.onThirdCall();
3119 withArgs
: function withArgs(/* arguments */) {
3121 "Defining a stub by invoking \"stub.onCall(...).withArgs(...)\" " +
3122 "is not supported. Use \"stub.withArgs(...).onCall(...)\" " +
3123 "to define sequential behavior for calls with certain arguments."
3127 callsArg
: function callsArg(pos
) {
3128 if (typeof pos
!== "number") {
3129 throw new TypeError("argument index is not number");
3132 this.callArgAt
= pos
;
3133 this.callbackArguments
= [];
3134 this.callbackContext
= undefined;
3135 this.callArgProp
= undefined;
3136 this.callbackAsync
= false;
3141 callsArgOn
: function callsArgOn(pos
, context
) {
3142 if (typeof pos
!== "number") {
3143 throw new TypeError("argument index is not number");
3145 if (typeof context
!== "object") {
3146 throw new TypeError("argument context is not an object");
3149 this.callArgAt
= pos
;
3150 this.callbackArguments
= [];
3151 this.callbackContext
= context
;
3152 this.callArgProp
= undefined;
3153 this.callbackAsync
= false;
3158 callsArgWith
: function callsArgWith(pos
) {
3159 if (typeof pos
!== "number") {
3160 throw new TypeError("argument index is not number");
3163 this.callArgAt
= pos
;
3164 this.callbackArguments
= slice
.call(arguments
, 1);
3165 this.callbackContext
= undefined;
3166 this.callArgProp
= undefined;
3167 this.callbackAsync
= false;
3172 callsArgOnWith
: function callsArgWith(pos
, context
) {
3173 if (typeof pos
!== "number") {
3174 throw new TypeError("argument index is not number");
3176 if (typeof context
!== "object") {
3177 throw new TypeError("argument context is not an object");
3180 this.callArgAt
= pos
;
3181 this.callbackArguments
= slice
.call(arguments
, 2);
3182 this.callbackContext
= context
;
3183 this.callArgProp
= undefined;
3184 this.callbackAsync
= false;
3189 yields: function () {
3190 this.callArgAt
= useLeftMostCallback
;
3191 this.callbackArguments
= slice
.call(arguments
, 0);
3192 this.callbackContext
= undefined;
3193 this.callArgProp
= undefined;
3194 this.callbackAsync
= false;
3199 yieldsRight: function () {
3200 this.callArgAt
= useRightMostCallback
;
3201 this.callbackArguments
= slice
.call(arguments
, 0);
3202 this.callbackContext
= undefined;
3203 this.callArgProp
= undefined;
3204 this.callbackAsync
= false;
3209 yieldsOn: function (context
) {
3210 if (typeof context
!== "object") {
3211 throw new TypeError("argument context is not an object");
3214 this.callArgAt
= useLeftMostCallback
;
3215 this.callbackArguments
= slice
.call(arguments
, 1);
3216 this.callbackContext
= context
;
3217 this.callArgProp
= undefined;
3218 this.callbackAsync
= false;
3223 yieldsTo: function (prop
) {
3224 this.callArgAt
= useLeftMostCallback
;
3225 this.callbackArguments
= slice
.call(arguments
, 1);
3226 this.callbackContext
= undefined;
3227 this.callArgProp
= prop
;
3228 this.callbackAsync
= false;
3233 yieldsToOn: function (prop
, context
) {
3234 if (typeof context
!== "object") {
3235 throw new TypeError("argument context is not an object");
3238 this.callArgAt
= useLeftMostCallback
;
3239 this.callbackArguments
= slice
.call(arguments
, 2);
3240 this.callbackContext
= context
;
3241 this.callArgProp
= prop
;
3242 this.callbackAsync
= false;
3247 throws: throwsException
,
3248 throwsException
: throwsException
,
3250 returns
: function returns(value
) {
3251 this.returnValue
= value
;
3252 this.returnValueDefined
= true;
3253 this.exception
= undefined;
3258 returnsArg
: function returnsArg(pos
) {
3259 if (typeof pos
!== "number") {
3260 throw new TypeError("argument index is not number");
3263 this.returnArgAt
= pos
;
3268 returnsThis
: function returnsThis() {
3269 this.returnThis
= true;
3275 function createAsyncVersion(syncFnName
) {
3276 return function () {
3277 var result
= this[syncFnName
].apply(this, arguments
);
3278 this.callbackAsync
= true;
3283 // create asynchronous versions of callsArg* and yields* methods
3284 for (var method
in proto
) {
3285 // need to avoid creating anotherasync versions of the newly added async methods
3286 if (proto
.hasOwnProperty(method
) && method
.match(/^(callsArg|yields)/) && !method
.match(/Async/)) {
3287 proto
[method
+ "Async"] = createAsyncVersion(method
);
3291 sinon
.behavior
= proto
;
3295 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
3296 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
3298 function loadDependencies(require
, exports
, module
) {
3299 var sinon
= require("./util/core");
3300 require("./extend");
3301 module
.exports
= makeApi(sinon
);
3305 define(loadDependencies
);
3310 loadDependencies(require
, module
.exports
, module
);
3315 makeApi(sinonGlobal
);
3318 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
3322 * @depend util/core.js
3324 (function (sinonGlobal
) {
3326 function makeApi(sinon
) {
3327 function walkInternal(obj
, iterator
, context
, originalObj
, seen
) {
3330 if (typeof Object
.getOwnPropertyNames
!== "function") {
3331 // We explicitly want to enumerate through all of the prototype's properties
3332 // in this case, therefore we deliberately leave out an own property check.
3333 /* eslint-disable guard-for-in */
3335 iterator
.call(context
, obj
[prop
], prop
, obj
);
3337 /* eslint-enable guard-for-in */
3342 Object
.getOwnPropertyNames(obj
).forEach(function (k
) {
3345 var target
= typeof Object
.getOwnPropertyDescriptor(obj
, k
).get === "function" ?
3347 iterator
.call(context
, target
[k
], k
, target
);
3351 proto
= Object
.getPrototypeOf(obj
);
3353 walkInternal(proto
, iterator
, context
, originalObj
, seen
);
3357 /* Public: walks the prototype chain of an object and iterates over every own property
3358 * name encountered. The iterator is called in the same fashion that Array.prototype.forEach
3359 * works, where it is passed the value, key, and own object as the 1st, 2nd, and 3rd positional
3360 * argument, respectively. In cases where Object.getOwnPropertyNames is not available, walk will
3361 * default to using a simple for..in loop.
3363 * obj - The object to walk the prototype chain for.
3364 * iterator - The function to be called on each pass of the walk.
3365 * context - (Optional) When given, the iterator will be called with this object as the receiver.
3367 function walk(obj
, iterator
, context
) {
3368 return walkInternal(obj
, iterator
, context
, obj
, {});
3375 function loadDependencies(require
, exports
, module
) {
3376 var sinon
= require("./util/core");
3377 module
.exports
= makeApi(sinon
);
3380 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
3381 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
3384 define(loadDependencies
);
3389 loadDependencies(require
, module
.exports
, module
);
3394 makeApi(sinonGlobal
);
3397 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
3401 * @depend util/core.js
3404 * @depend behavior.js
3410 * @author Christian Johansen (christian@cjohansen.no)
3413 * Copyright (c) 2010-2013 Christian Johansen
3415 (function (sinonGlobal
) {
3417 function makeApi(sinon
) {
3418 function stub(object
, property
, func
) {
3419 if (!!func
&& typeof func
!== "function" && typeof func
!== "object") {
3420 throw new TypeError("Custom stub should be a function or a property descriptor");
3426 if (typeof func
=== "function") {
3427 wrapper
= sinon
.spy
&& sinon
.spy
.create
? sinon
.spy
.create(func
) : func
;
3430 if (sinon
.spy
&& sinon
.spy
.create
) {
3431 var types
= sinon
.objectKeys(wrapper
);
3432 for (var i
= 0; i
< types
.length
; i
++) {
3433 wrapper
[types
[i
]] = sinon
.spy
.create(wrapper
[types
[i
]]);
3439 if (typeof object
=== "object" && typeof object
[property
] === "function") {
3440 stubLength
= object
[property
].length
;
3442 wrapper
= stub
.create(stubLength
);
3445 if (!object
&& typeof property
=== "undefined") {
3446 return sinon
.stub
.create();
3449 if (typeof property
=== "undefined" && typeof object
=== "object") {
3450 sinon
.walk(object
|| {}, function (value
, prop
, propOwner
) {
3451 // we don't want to stub things like toString(), valueOf(), etc. so we only stub if the object
3452 // is not Object.prototype
3454 propOwner
!== Object
.prototype &&
3455 prop
!== "constructor" &&
3456 typeof sinon
.getPropertyDescriptor(propOwner
, prop
).value
=== "function"
3465 return sinon
.wrapMethod(object
, property
, wrapper
);
3469 /*eslint-disable no-use-before-define*/
3470 function getParentBehaviour(stubInstance
) {
3471 return (stubInstance
.parent
&& getCurrentBehavior(stubInstance
.parent
));
3474 function getDefaultBehavior(stubInstance
) {
3475 return stubInstance
.defaultBehavior
||
3476 getParentBehaviour(stubInstance
) ||
3477 sinon
.behavior
.create(stubInstance
);
3480 function getCurrentBehavior(stubInstance
) {
3481 var behavior
= stubInstance
.behaviors
[stubInstance
.callCount
- 1];
3482 return behavior
&& behavior
.isPresent() ? behavior
: getDefaultBehavior(stubInstance
);
3484 /*eslint-enable no-use-before-define*/
3489 create
: function create(stubLength
) {
3490 var functionStub = function () {
3491 return getCurrentBehavior(functionStub
).invoke(this, arguments
);
3494 functionStub
.id
= "stub#" + uuid
++;
3495 var orig
= functionStub
;
3496 functionStub
= sinon
.spy
.create(functionStub
, stubLength
);
3497 functionStub
.func
= orig
;
3499 sinon
.extend(functionStub
, stub
);
3500 functionStub
.instantiateFake
= sinon
.stub
.create
;
3501 functionStub
.displayName
= "stub";
3502 functionStub
.toString
= sinon
.functionToString
;
3504 functionStub
.defaultBehavior
= null;
3505 functionStub
.behaviors
= [];
3507 return functionStub
;
3510 resetBehavior: function () {
3513 this.defaultBehavior
= null;
3514 this.behaviors
= [];
3516 delete this.returnValue
;
3517 delete this.returnArgAt
;
3518 this.returnThis
= false;
3521 for (i
= 0; i
< this.fakes
.length
; i
++) {
3522 this.fakes
[i
].resetBehavior();
3527 onCall
: function onCall(index
) {
3528 if (!this.behaviors
[index
]) {
3529 this.behaviors
[index
] = sinon
.behavior
.create(this);
3532 return this.behaviors
[index
];
3535 onFirstCall
: function onFirstCall() {
3536 return this.onCall(0);
3539 onSecondCall
: function onSecondCall() {
3540 return this.onCall(1);
3543 onThirdCall
: function onThirdCall() {
3544 return this.onCall(2);
3548 function createBehavior(behaviorMethod
) {
3549 return function () {
3550 this.defaultBehavior
= this.defaultBehavior
|| sinon
.behavior
.create(this);
3551 this.defaultBehavior
[behaviorMethod
].apply(this.defaultBehavior
, arguments
);
3556 for (var method
in sinon
.behavior
) {
3557 if (sinon
.behavior
.hasOwnProperty(method
) &&
3558 !proto
.hasOwnProperty(method
) &&
3559 method
!== "create" &&
3560 method
!== "withArgs" &&
3561 method
!== "invoke") {
3562 proto
[method
] = createBehavior(method
);
3566 sinon
.extend(stub
, proto
);
3572 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
3573 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
3575 function loadDependencies(require
, exports
, module
) {
3576 var core
= require("./util/core");
3577 require("./behavior");
3579 require("./extend");
3580 module
.exports
= makeApi(core
);
3584 define(loadDependencies
);
3589 loadDependencies(require
, module
.exports
, module
);
3594 makeApi(sinonGlobal
);
3597 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
3601 * @depend times_in_words.js
3602 * @depend util/core.js
3613 * @author Christian Johansen (christian@cjohansen.no)
3616 * Copyright (c) 2010-2013 Christian Johansen
3618 (function (sinonGlobal
) {
3620 function makeApi(sinon
) {
3622 var match
= sinon
.match
;
3624 function mock(object
) {
3625 // if (typeof console !== undefined && console.warn) {
3626 // console.warn("mock will be removed from Sinon.JS v2.0");
3630 return sinon
.expectation
.create("Anonymous mock");
3633 return mock
.create(object
);
3636 function each(collection
, callback
) {
3641 for (var i
= 0, l
= collection
.length
; i
< l
; i
+= 1) {
3642 callback(collection
[i
]);
3646 function arrayEquals(arr1
, arr2
, compareLength
) {
3647 if (compareLength
&& (arr1
.length
!== arr2
.length
)) {
3651 for (var i
= 0, l
= arr1
.length
; i
< l
; i
++) {
3652 if (!sinon
.deepEqual(arr1
[i
], arr2
[i
])) {
3659 sinon
.extend(mock
, {
3660 create
: function create(object
) {
3662 throw new TypeError("object is null");
3665 var mockObject
= sinon
.extend({}, mock
);
3666 mockObject
.object
= object
;
3667 delete mockObject
.create
;
3672 expects
: function expects(method
) {
3674 throw new TypeError("method is falsy");
3677 if (!this.expectations
) {
3678 this.expectations
= {};
3682 if (!this.expectations
[method
]) {
3683 this.expectations
[method
] = [];
3684 var mockObject
= this;
3686 sinon
.wrapMethod(this.object
, method
, function () {
3687 return mockObject
.invokeMethod(method
, this, arguments
);
3690 push
.call(this.proxies
, method
);
3693 var expectation
= sinon
.expectation
.create(method
);
3694 push
.call(this.expectations
[method
], expectation
);
3699 restore
: function restore() {
3700 var object
= this.object
;
3702 each(this.proxies
, function (proxy
) {
3703 if (typeof object
[proxy
].restore
=== "function") {
3704 object
[proxy
].restore();
3709 verify
: function verify() {
3710 var expectations
= this.expectations
|| {};
3714 each(this.proxies
, function (proxy
) {
3715 each(expectations
[proxy
], function (expectation
) {
3716 if (!expectation
.met()) {
3717 push
.call(messages
, expectation
.toString());
3719 push
.call(met
, expectation
.toString());
3726 if (messages
.length
> 0) {
3727 sinon
.expectation
.fail(messages
.concat(met
).join("\n"));
3728 } else if (met
.length
> 0) {
3729 sinon
.expectation
.pass(messages
.concat(met
).join("\n"));
3735 invokeMethod
: function invokeMethod(method
, thisValue
, args
) {
3736 var expectations
= this.expectations
&& this.expectations
[method
] ? this.expectations
[method
] : [];
3737 var expectationsWithMatchingArgs
= [];
3738 var currentArgs
= args
|| [];
3741 for (i
= 0; i
< expectations
.length
; i
+= 1) {
3742 var expectedArgs
= expectations
[i
].expectedArguments
|| [];
3743 if (arrayEquals(expectedArgs
, currentArgs
, expectations
[i
].expectsExactArgCount
)) {
3744 expectationsWithMatchingArgs
.push(expectations
[i
]);
3748 for (i
= 0; i
< expectationsWithMatchingArgs
.length
; i
+= 1) {
3749 if (!expectationsWithMatchingArgs
[i
].met() &&
3750 expectationsWithMatchingArgs
[i
].allowsCall(thisValue
, args
)) {
3751 return expectationsWithMatchingArgs
[i
].apply(thisValue
, args
);
3758 for (i
= 0; i
< expectationsWithMatchingArgs
.length
; i
+= 1) {
3759 if (expectationsWithMatchingArgs
[i
].allowsCall(thisValue
, args
)) {
3760 available
= available
|| expectationsWithMatchingArgs
[i
];
3766 if (available
&& exhausted
=== 0) {
3767 return available
.apply(thisValue
, args
);
3770 for (i
= 0; i
< expectations
.length
; i
+= 1) {
3771 push
.call(messages
, " " + expectations
[i
].toString());
3774 messages
.unshift("Unexpected call: " + sinon
.spyCall
.toString
.call({
3779 sinon
.expectation
.fail(messages
.join("\n"));
3783 var times
= sinon
.timesInWords
;
3784 var slice
= Array
.prototype.slice
;
3786 function callCountInWords(callCount
) {
3787 if (callCount
=== 0) {
3788 return "never called";
3791 return "called " + times(callCount
);
3794 function expectedCallCountInWords(expectation
) {
3795 var min
= expectation
.minCalls
;
3796 var max
= expectation
.maxCalls
;
3798 if (typeof min
=== "number" && typeof max
=== "number") {
3799 var str
= times(min
);
3802 str
= "at least " + str
+ " and at most " + times(max
);
3808 if (typeof min
=== "number") {
3809 return "at least " + times(min
);
3812 return "at most " + times(max
);
3815 function receivedMinCalls(expectation
) {
3816 var hasMinLimit
= typeof expectation
.minCalls
=== "number";
3817 return !hasMinLimit
|| expectation
.callCount
>= expectation
.minCalls
;
3820 function receivedMaxCalls(expectation
) {
3821 if (typeof expectation
.maxCalls
!== "number") {
3825 return expectation
.callCount
=== expectation
.maxCalls
;
3828 function verifyMatcher(possibleMatcher
, arg
) {
3829 var isMatcher
= match
&& match
.isMatcher(possibleMatcher
);
3831 return isMatcher
&& possibleMatcher
.test(arg
) || true;
3834 sinon
.expectation
= {
3838 create
: function create(methodName
) {
3839 var expectation
= sinon
.extend(sinon
.stub
.create(), sinon
.expectation
);
3840 delete expectation
.create
;
3841 expectation
.method
= methodName
;
3846 invoke
: function invoke(func
, thisValue
, args
) {
3847 this.verifyCallAllowed(thisValue
, args
);
3849 return sinon
.spy
.invoke
.apply(this, arguments
);
3852 atLeast
: function atLeast(num
) {
3853 if (typeof num
!== "number") {
3854 throw new TypeError("'" + num
+ "' is not number");
3857 if (!this.limitsSet
) {
3858 this.maxCalls
= null;
3859 this.limitsSet
= true;
3862 this.minCalls
= num
;
3867 atMost
: function atMost(num
) {
3868 if (typeof num
!== "number") {
3869 throw new TypeError("'" + num
+ "' is not number");
3872 if (!this.limitsSet
) {
3873 this.minCalls
= null;
3874 this.limitsSet
= true;
3877 this.maxCalls
= num
;
3882 never
: function never() {
3883 return this.exactly(0);
3886 once
: function once() {
3887 return this.exactly(1);
3890 twice
: function twice() {
3891 return this.exactly(2);
3894 thrice
: function thrice() {
3895 return this.exactly(3);
3898 exactly
: function exactly(num
) {
3899 if (typeof num
!== "number") {
3900 throw new TypeError("'" + num
+ "' is not a number");
3904 return this.atMost(num
);
3907 met
: function met() {
3908 return !this.failed
&& receivedMinCalls(this);
3911 verifyCallAllowed
: function verifyCallAllowed(thisValue
, args
) {
3912 if (receivedMaxCalls(this)) {
3914 sinon
.expectation
.fail(this.method
+ " already called " + times(this.maxCalls
));
3917 if ("expectedThis" in this && this.expectedThis
!== thisValue
) {
3918 sinon
.expectation
.fail(this.method
+ " called with " + thisValue
+ " as thisValue, expected " +
3922 if (!("expectedArguments" in this)) {
3927 sinon
.expectation
.fail(this.method
+ " received no arguments, expected " +
3928 sinon
.format(this.expectedArguments
));
3931 if (args
.length
< this.expectedArguments
.length
) {
3932 sinon
.expectation
.fail(this.method
+ " received too few arguments (" + sinon
.format(args
) +
3933 "), expected " + sinon
.format(this.expectedArguments
));
3936 if (this.expectsExactArgCount
&&
3937 args
.length
!== this.expectedArguments
.length
) {
3938 sinon
.expectation
.fail(this.method
+ " received too many arguments (" + sinon
.format(args
) +
3939 "), expected " + sinon
.format(this.expectedArguments
));
3942 for (var i
= 0, l
= this.expectedArguments
.length
; i
< l
; i
+= 1) {
3944 if (!verifyMatcher(this.expectedArguments
[i
], args
[i
])) {
3945 sinon
.expectation
.fail(this.method
+ " received wrong arguments " + sinon
.format(args
) +
3946 ", didn't match " + this.expectedArguments
.toString());
3949 if (!sinon
.deepEqual(this.expectedArguments
[i
], args
[i
])) {
3950 sinon
.expectation
.fail(this.method
+ " received wrong arguments " + sinon
.format(args
) +
3951 ", expected " + sinon
.format(this.expectedArguments
));
3956 allowsCall
: function allowsCall(thisValue
, args
) {
3957 if (this.met() && receivedMaxCalls(this)) {
3961 if ("expectedThis" in this && this.expectedThis
!== thisValue
) {
3965 if (!("expectedArguments" in this)) {
3971 if (args
.length
< this.expectedArguments
.length
) {
3975 if (this.expectsExactArgCount
&&
3976 args
.length
!== this.expectedArguments
.length
) {
3980 for (var i
= 0, l
= this.expectedArguments
.length
; i
< l
; i
+= 1) {
3981 if (!verifyMatcher(this.expectedArguments
[i
], args
[i
])) {
3985 if (!sinon
.deepEqual(this.expectedArguments
[i
], args
[i
])) {
3993 withArgs
: function withArgs() {
3994 this.expectedArguments
= slice
.call(arguments
);
3998 withExactArgs
: function withExactArgs() {
3999 this.withArgs
.apply(this, arguments
);
4000 this.expectsExactArgCount
= true;
4004 on
: function on(thisValue
) {
4005 this.expectedThis
= thisValue
;
4009 toString: function () {
4010 var args
= (this.expectedArguments
|| []).slice();
4012 if (!this.expectsExactArgCount
) {
4013 push
.call(args
, "[...]");
4016 var callStr
= sinon
.spyCall
.toString
.call({
4017 proxy
: this.method
|| "anonymous mock expectation",
4021 var message
= callStr
.replace(", [...", "[, ...") + " " +
4022 expectedCallCountInWords(this);
4025 return "Expectation met: " + message
;
4028 return "Expected " + message
+ " (" +
4029 callCountInWords(this.callCount
) + ")";
4032 verify
: function verify() {
4034 sinon
.expectation
.fail(this.toString());
4036 sinon
.expectation
.pass(this.toString());
4042 pass
: function pass(message
) {
4043 sinon
.assert
.pass(message
);
4046 fail
: function fail(message
) {
4047 var exception
= new Error(message
);
4048 exception
.name
= "ExpectationError";
4058 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
4059 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
4061 function loadDependencies(require
, exports
, module
) {
4062 var sinon
= require("./util/core");
4063 require("./times_in_words");
4065 require("./extend");
4069 require("./format");
4071 module
.exports
= makeApi(sinon
);
4075 define(loadDependencies
);
4080 loadDependencies(require
, module
.exports
, module
);
4085 makeApi(sinonGlobal
);
4088 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
4092 * @depend util/core.js
4098 * Collections of stubs, spies and mocks.
4100 * @author Christian Johansen (christian@cjohansen.no)
4103 * Copyright (c) 2010-2013 Christian Johansen
4105 (function (sinonGlobal
) {
4108 var hasOwnProperty
= Object
.prototype.hasOwnProperty
;
4110 function getFakes(fakeCollection
) {
4111 if (!fakeCollection
.fakes
) {
4112 fakeCollection
.fakes
= [];
4115 return fakeCollection
.fakes
;
4118 function each(fakeCollection
, method
) {
4119 var fakes
= getFakes(fakeCollection
);
4121 for (var i
= 0, l
= fakes
.length
; i
< l
; i
+= 1) {
4122 if (typeof fakes
[i
][method
] === "function") {
4128 function compact(fakeCollection
) {
4129 var fakes
= getFakes(fakeCollection
);
4131 while (i
< fakes
.length
) {
4136 function makeApi(sinon
) {
4138 verify
: function resolve() {
4139 each(this, "verify");
4142 restore
: function restore() {
4143 each(this, "restore");
4147 reset
: function restore() {
4148 each(this, "reset");
4151 verifyAndRestore
: function verifyAndRestore() {
4167 add
: function add(fake
) {
4168 push
.call(getFakes(this), fake
);
4172 spy
: function spy() {
4173 return this.add(sinon
.spy
.apply(sinon
, arguments
));
4176 stub
: function stub(object
, property
, value
) {
4178 var original
= object
[property
];
4180 if (typeof original
!== "function") {
4181 if (!hasOwnProperty
.call(object
, property
)) {
4182 throw new TypeError("Cannot stub non-existent own property " + property
);
4185 object
[property
] = value
;
4188 restore: function () {
4189 object
[property
] = original
;
4194 if (!property
&& !!object
&& typeof object
=== "object") {
4195 var stubbedObj
= sinon
.stub
.apply(sinon
, arguments
);
4197 for (var prop
in stubbedObj
) {
4198 if (typeof stubbedObj
[prop
] === "function") {
4199 this.add(stubbedObj
[prop
]);
4206 return this.add(sinon
.stub
.apply(sinon
, arguments
));
4209 mock
: function mock() {
4210 return this.add(sinon
.mock
.apply(sinon
, arguments
));
4213 inject
: function inject(obj
) {
4216 obj
.spy = function () {
4217 return col
.spy
.apply(col
, arguments
);
4220 obj
.stub = function () {
4221 return col
.stub
.apply(col
, arguments
);
4224 obj
.mock = function () {
4225 return col
.mock
.apply(col
, arguments
);
4232 sinon
.collection
= collection
;
4236 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
4237 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
4239 function loadDependencies(require
, exports
, module
) {
4240 var sinon
= require("./util/core");
4244 module
.exports
= makeApi(sinon
);
4248 define(loadDependencies
);
4253 loadDependencies(require
, module
.exports
, module
);
4258 makeApi(sinonGlobal
);
4261 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
4274 * Inspired by jsUnitMockTimeOut from JsUnit
4276 * @author Christian Johansen (christian@cjohansen.no)
4279 * Copyright (c) 2010-2013 Christian Johansen
4283 function makeApi(s
, lol
) {
4285 var llx
= typeof lolex
!== "undefined" ? lolex
: lol
;
4287 s
.useFakeTimers = function () {
4289 var methods
= Array
.prototype.slice
.call(arguments
);
4291 if (typeof methods
[0] === "string") {
4294 now
= methods
.shift();
4297 var clock
= llx
.install(now
|| 0, methods
);
4298 clock
.restore
= clock
.uninstall
;
4303 create: function (now
) {
4304 return llx
.createClock(now
);
4309 setTimeout
: setTimeout
,
4310 clearTimeout
: clearTimeout
,
4311 setImmediate
: (typeof setImmediate
!== "undefined" ? setImmediate
: undefined),
4312 clearImmediate
: (typeof clearImmediate
!== "undefined" ? clearImmediate
: undefined),
4313 setInterval
: setInterval
,
4314 clearInterval
: clearInterval
,
4319 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
4320 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
4322 function loadDependencies(require
, epxorts
, module
, lolex
) {
4323 var core
= require("./core");
4324 makeApi(core
, lolex
);
4325 module
.exports
= core
;
4329 define(loadDependencies
);
4330 } else if (isNode
) {
4331 loadDependencies(require
, module
.exports
, module
, require("lolex"));
4333 makeApi(sinon
); // eslint-disable-line no-undef
4338 * Minimal Event interface implementation
4340 * Original implementation by Sven Fuchs: https://gist.github.com/995028
4341 * Modifications and tests by Christian Johansen.
4343 * @author Sven Fuchs (svenfuchs@artweb-design.de)
4344 * @author Christian Johansen (christian@cjohansen.no)
4347 * Copyright (c) 2011 Sven Fuchs, Christian Johansen
4349 if (typeof sinon
=== "undefined") {
4357 function makeApi(sinon
) {
4358 sinon
.Event
= function Event(type
, bubbles
, cancelable
, target
) {
4359 this.initEvent(type
, bubbles
, cancelable
, target
);
4362 sinon
.Event
.prototype = {
4363 initEvent: function (type
, bubbles
, cancelable
, target
) {
4365 this.bubbles
= bubbles
;
4366 this.cancelable
= cancelable
;
4367 this.target
= target
;
4370 stopPropagation: function () {},
4372 preventDefault: function () {
4373 this.defaultPrevented
= true;
4377 sinon
.ProgressEvent
= function ProgressEvent(type
, progressEventRaw
, target
) {
4378 this.initEvent(type
, false, false, target
);
4379 this.loaded
= progressEventRaw
.loaded
|| null;
4380 this.total
= progressEventRaw
.total
|| null;
4381 this.lengthComputable
= !!progressEventRaw
.total
;
4384 sinon
.ProgressEvent
.prototype = new sinon
.Event();
4386 sinon
.ProgressEvent
.prototype.constructor = sinon
.ProgressEvent
;
4388 sinon
.CustomEvent
= function CustomEvent(type
, customData
, target
) {
4389 this.initEvent(type
, false, false, target
);
4390 this.detail
= customData
.detail
|| null;
4393 sinon
.CustomEvent
.prototype = new sinon
.Event();
4395 sinon
.CustomEvent
.prototype.constructor = sinon
.CustomEvent
;
4397 sinon
.EventTarget
= {
4398 addEventListener
: function addEventListener(event
, listener
) {
4399 this.eventListeners
= this.eventListeners
|| {};
4400 this.eventListeners
[event
] = this.eventListeners
[event
] || [];
4401 push
.call(this.eventListeners
[event
], listener
);
4404 removeEventListener
: function removeEventListener(event
, listener
) {
4405 var listeners
= this.eventListeners
&& this.eventListeners
[event
] || [];
4407 for (var i
= 0, l
= listeners
.length
; i
< l
; ++i
) {
4408 if (listeners
[i
] === listener
) {
4409 return listeners
.splice(i
, 1);
4414 dispatchEvent
: function dispatchEvent(event
) {
4415 var type
= event
.type
;
4416 var listeners
= this.eventListeners
&& this.eventListeners
[type
] || [];
4418 for (var i
= 0; i
< listeners
.length
; i
++) {
4419 if (typeof listeners
[i
] === "function") {
4420 listeners
[i
].call(this, event
);
4422 listeners
[i
].handleEvent(event
);
4426 return !!event
.defaultPrevented
;
4431 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
4432 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
4434 function loadDependencies(require
) {
4435 var sinon
= require("./core");
4440 define(loadDependencies
);
4441 } else if (isNode
) {
4442 loadDependencies(require
);
4444 makeApi(sinon
); // eslint-disable-line no-undef
4449 * @depend util/core.js
4454 * @author Christian Johansen (christian@cjohansen.no)
4457 * Copyright (c) 2010-2014 Christian Johansen
4459 (function (sinonGlobal
) {
4461 // cache a reference to setTimeout, so that our reference won't be stubbed out
4462 // when using fake timers and errors will still get logged
4463 // https://github.com/cjohansen/Sinon.JS/issues/381
4464 var realSetTimeout
= setTimeout
;
4466 function makeApi(sinon
) {
4470 function logError(label
, err
) {
4471 var msg
= label
+ " threw exception: ";
4473 function throwLoggedError() {
4474 err
.message
= msg
+ err
.message
;
4478 sinon
.log(msg
+ "[" + err
.name
+ "] " + err
.message
);
4481 sinon
.log(err
.stack
);
4484 if (logError
.useImmediateExceptions
) {
4487 logError
.setTimeout(throwLoggedError
, 0);
4491 // When set to true, any errors logged will be thrown immediately;
4492 // If set to false, the errors will be thrown in separate execution frame.
4493 logError
.useImmediateExceptions
= false;
4495 // wrap realSetTimeout with something we can stub in tests
4496 logError
.setTimeout = function (func
, timeout
) {
4497 realSetTimeout(func
, timeout
);
4501 exports
.log
= sinon
.log
= log
;
4502 exports
.logError
= sinon
.logError
= logError
;
4507 function loadDependencies(require
, exports
, module
) {
4508 var sinon
= require("./util/core");
4509 module
.exports
= makeApi(sinon
);
4512 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
4513 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
4516 define(loadDependencies
);
4521 loadDependencies(require
, module
.exports
, module
);
4526 makeApi(sinonGlobal
);
4529 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
4534 * @depend ../extend.js
4536 * @depend ../log_error.js
4539 * Fake XDomainRequest object
4543 * Returns the global to prevent assigning values to 'this' when this is undefined.
4544 * This can occur when files are interpreted by node in strict mode.
4547 function getGlobal() {
4549 return typeof window
!== "undefined" ? window
: global
;
4552 if (typeof sinon
=== "undefined") {
4553 if (typeof this === "undefined") {
4554 getGlobal().sinon
= {};
4560 // wrapper for global
4561 (function (global
) {
4563 var xdr
= { XDomainRequest
: global
.XDomainRequest
};
4564 xdr
.GlobalXDomainRequest
= global
.XDomainRequest
;
4565 xdr
.supportsXDR
= typeof xdr
.GlobalXDomainRequest
!== "undefined";
4566 xdr
.workingXDR
= xdr
.supportsXDR
? xdr
.GlobalXDomainRequest
: false;
4568 function makeApi(sinon
) {
4571 function FakeXDomainRequest() {
4572 this.readyState
= FakeXDomainRequest
.UNSENT
;
4573 this.requestBody
= null;
4574 this.requestHeaders
= {};
4576 this.timeout
= null;
4578 if (typeof FakeXDomainRequest
.onCreate
=== "function") {
4579 FakeXDomainRequest
.onCreate(this);
4583 function verifyState(x
) {
4584 if (x
.readyState
!== FakeXDomainRequest
.OPENED
) {
4585 throw new Error("INVALID_STATE_ERR");
4589 throw new Error("INVALID_STATE_ERR");
4593 function verifyRequestSent(x
) {
4594 if (x
.readyState
=== FakeXDomainRequest
.UNSENT
) {
4595 throw new Error("Request not sent");
4597 if (x
.readyState
=== FakeXDomainRequest
.DONE
) {
4598 throw new Error("Request done");
4602 function verifyResponseBodyType(body
) {
4603 if (typeof body
!== "string") {
4604 var error
= new Error("Attempted to respond to fake XDomainRequest with " +
4605 body
+ ", which is not a string.");
4606 error
.name
= "InvalidBodyException";
4611 sinon
.extend(FakeXDomainRequest
.prototype, sinon
.EventTarget
, {
4612 open
: function open(method
, url
) {
4613 this.method
= method
;
4616 this.responseText
= null;
4617 this.sendFlag
= false;
4619 this.readyStateChange(FakeXDomainRequest
.OPENED
);
4622 readyStateChange
: function readyStateChange(state
) {
4623 this.readyState
= state
;
4625 switch (this.readyState
) {
4626 case FakeXDomainRequest
.UNSENT
:
4628 case FakeXDomainRequest
.OPENED
:
4630 case FakeXDomainRequest
.LOADING
:
4631 if (this.sendFlag
) {
4632 //raise the progress event
4633 eventName
= "onprogress";
4636 case FakeXDomainRequest
.DONE
:
4637 if (this.isTimeout
) {
4638 eventName
= "ontimeout";
4639 } else if (this.errorFlag
|| (this.status
< 200 || this.status
> 299)) {
4640 eventName
= "onerror";
4642 eventName
= "onload";
4647 // raising event (if defined)
4649 if (typeof this[eventName
] === "function") {
4653 sinon
.logError("Fake XHR " + eventName
+ " handler", e
);
4659 send
: function send(data
) {
4662 if (!/^(get|head)$/i.test(this.method
)) {
4663 this.requestBody
= data
;
4665 this.requestHeaders
["Content-Type"] = "text/plain;charset=utf-8";
4667 this.errorFlag
= false;
4668 this.sendFlag
= true;
4669 this.readyStateChange(FakeXDomainRequest
.OPENED
);
4671 if (typeof this.onSend
=== "function") {
4676 abort
: function abort() {
4677 this.aborted
= true;
4678 this.responseText
= null;
4679 this.errorFlag
= true;
4681 if (this.readyState
> sinon
.FakeXDomainRequest
.UNSENT
&& this.sendFlag
) {
4682 this.readyStateChange(sinon
.FakeXDomainRequest
.DONE
);
4683 this.sendFlag
= false;
4687 setResponseBody
: function setResponseBody(body
) {
4688 verifyRequestSent(this);
4689 verifyResponseBodyType(body
);
4691 var chunkSize
= this.chunkSize
|| 10;
4693 this.responseText
= "";
4696 this.readyStateChange(FakeXDomainRequest
.LOADING
);
4697 this.responseText
+= body
.substring(index
, index
+ chunkSize
);
4699 } while (index
< body
.length
);
4701 this.readyStateChange(FakeXDomainRequest
.DONE
);
4704 respond
: function respond(status
, contentType
, body
) {
4705 // content-type ignored, since XDomainRequest does not carry this
4706 // we keep the same syntax for respond(...) as for FakeXMLHttpRequest to ease
4707 // test integration across browsers
4708 this.status
= typeof status
=== "number" ? status
: 200;
4709 this.setResponseBody(body
|| "");
4712 simulatetimeout
: function simulatetimeout() {
4714 this.isTimeout
= true;
4715 // Access to this should actually throw an error
4716 this.responseText
= undefined;
4717 this.readyStateChange(FakeXDomainRequest
.DONE
);
4721 sinon
.extend(FakeXDomainRequest
, {
4728 sinon
.useFakeXDomainRequest
= function useFakeXDomainRequest() {
4729 sinon
.FakeXDomainRequest
.restore
= function restore(keepOnCreate
) {
4730 if (xdr
.supportsXDR
) {
4731 global
.XDomainRequest
= xdr
.GlobalXDomainRequest
;
4734 delete sinon
.FakeXDomainRequest
.restore
;
4736 if (keepOnCreate
!== true) {
4737 delete sinon
.FakeXDomainRequest
.onCreate
;
4740 if (xdr
.supportsXDR
) {
4741 global
.XDomainRequest
= sinon
.FakeXDomainRequest
;
4743 return sinon
.FakeXDomainRequest
;
4746 sinon
.FakeXDomainRequest
= FakeXDomainRequest
;
4749 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
4750 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
4752 function loadDependencies(require
, exports
, module
) {
4753 var sinon
= require("./core");
4754 require("../extend");
4756 require("../log_error");
4758 module
.exports
= sinon
;
4762 define(loadDependencies
);
4763 } else if (isNode
) {
4764 loadDependencies(require
, module
.exports
, module
);
4766 makeApi(sinon
); // eslint-disable-line no-undef
4768 })(typeof global
!== "undefined" ? global
: self
);
4772 * @depend ../extend.js
4774 * @depend ../log_error.js
4777 * Fake XMLHttpRequest object
4779 * @author Christian Johansen (christian@cjohansen.no)
4782 * Copyright (c) 2010-2013 Christian Johansen
4784 (function (sinonGlobal
, global
) {
4786 function getWorkingXHR(globalScope
) {
4787 var supportsXHR
= typeof globalScope
.XMLHttpRequest
!== "undefined";
4789 return globalScope
.XMLHttpRequest
;
4792 var supportsActiveX
= typeof globalScope
.ActiveXObject
!== "undefined";
4793 if (supportsActiveX
) {
4794 return function () {
4795 return new globalScope
.ActiveXObject("MSXML2.XMLHTTP.3.0");
4802 var supportsProgress
= typeof ProgressEvent
!== "undefined";
4803 var supportsCustomEvent
= typeof CustomEvent
!== "undefined";
4804 var supportsFormData
= typeof FormData
!== "undefined";
4805 var supportsArrayBuffer
= typeof ArrayBuffer
!== "undefined";
4806 var supportsBlob
= typeof Blob
=== "function";
4807 var sinonXhr
= { XMLHttpRequest
: global
.XMLHttpRequest
};
4808 sinonXhr
.GlobalXMLHttpRequest
= global
.XMLHttpRequest
;
4809 sinonXhr
.GlobalActiveXObject
= global
.ActiveXObject
;
4810 sinonXhr
.supportsActiveX
= typeof sinonXhr
.GlobalActiveXObject
!== "undefined";
4811 sinonXhr
.supportsXHR
= typeof sinonXhr
.GlobalXMLHttpRequest
!== "undefined";
4812 sinonXhr
.workingXHR
= getWorkingXHR(global
);
4813 sinonXhr
.supportsCORS
= sinonXhr
.supportsXHR
&& "withCredentials" in (new sinonXhr
.GlobalXMLHttpRequest());
4815 var unsafeHeaders
= {
4816 "Accept-Charset": true,
4817 "Accept-Encoding": true,
4819 "Content-Length": true,
4822 "Content-Transfer-Encoding": true,
4830 "Transfer-Encoding": true,
4836 // An upload object is created for each
4837 // FakeXMLHttpRequest and allows upload
4838 // events to be simulated using uploadProgress
4840 function UploadProgress() {
4841 this.eventListeners
= {
4849 UploadProgress
.prototype.addEventListener
= function addEventListener(event
, listener
) {
4850 this.eventListeners
[event
].push(listener
);
4853 UploadProgress
.prototype.removeEventListener
= function removeEventListener(event
, listener
) {
4854 var listeners
= this.eventListeners
[event
] || [];
4856 for (var i
= 0, l
= listeners
.length
; i
< l
; ++i
) {
4857 if (listeners
[i
] === listener
) {
4858 return listeners
.splice(i
, 1);
4863 UploadProgress
.prototype.dispatchEvent
= function dispatchEvent(event
) {
4864 var listeners
= this.eventListeners
[event
.type
] || [];
4866 for (var i
= 0, listener
; (listener
= listeners
[i
]) != null; i
++) {
4871 // Note that for FakeXMLHttpRequest to work pre ES5
4872 // we lose some of the alignment with the spec.
4873 // To ensure as close a match as possible,
4874 // set responseType before calling open, send or respond;
4875 function FakeXMLHttpRequest() {
4876 this.readyState
= FakeXMLHttpRequest
.UNSENT
;
4877 this.requestHeaders
= {};
4878 this.requestBody
= null;
4880 this.statusText
= "";
4881 this.upload
= new UploadProgress();
4882 this.responseType
= "";
4884 if (sinonXhr
.supportsCORS
) {
4885 this.withCredentials
= false;
4889 var events
= ["loadstart", "load", "abort", "loadend"];
4891 function addEventListener(eventName
) {
4892 xhr
.addEventListener(eventName
, function (event
) {
4893 var listener
= xhr
["on" + eventName
];
4895 if (listener
&& typeof listener
=== "function") {
4896 listener
.call(this, event
);
4901 for (var i
= events
.length
- 1; i
>= 0; i
--) {
4902 addEventListener(events
[i
]);
4905 if (typeof FakeXMLHttpRequest
.onCreate
=== "function") {
4906 FakeXMLHttpRequest
.onCreate(this);
4910 function verifyState(xhr
) {
4911 if (xhr
.readyState
!== FakeXMLHttpRequest
.OPENED
) {
4912 throw new Error("INVALID_STATE_ERR");
4916 throw new Error("INVALID_STATE_ERR");
4920 function getHeader(headers
, header
) {
4921 header
= header
.toLowerCase();
4923 for (var h
in headers
) {
4924 if (h
.toLowerCase() === header
) {
4932 // filtering to enable a white-list version of Sinon FakeXhr,
4933 // where whitelisted requests are passed through to real XHR
4934 function each(collection
, callback
) {
4939 for (var i
= 0, l
= collection
.length
; i
< l
; i
+= 1) {
4940 callback(collection
[i
]);
4943 function some(collection
, callback
) {
4944 for (var index
= 0; index
< collection
.length
; index
++) {
4945 if (callback(collection
[index
]) === true) {
4951 // largest arity in XHR is 5 - XHR#open
4952 var apply = function (obj
, method
, args
) {
4953 switch (args
.length
) {
4954 case 0: return obj
[method
]();
4955 case 1: return obj
[method
](args
[0]);
4956 case 2: return obj
[method
](args
[0], args
[1]);
4957 case 3: return obj
[method
](args
[0], args
[1], args
[2]);
4958 case 4: return obj
[method
](args
[0], args
[1], args
[2], args
[3]);
4959 case 5: return obj
[method
](args
[0], args
[1], args
[2], args
[3], args
[4]);
4963 FakeXMLHttpRequest
.filters
= [];
4964 FakeXMLHttpRequest
.addFilter
= function addFilter(fn
) {
4965 this.filters
.push(fn
);
4967 var IE6Re
= /MSIE 6/;
4968 FakeXMLHttpRequest
.defake
= function defake(fakeXhr
, xhrArgs
) {
4969 var xhr
= new sinonXhr
.workingXHR(); // eslint-disable-line new-cap
4976 "getResponseHeader",
4977 "getAllResponseHeaders",
4980 "removeEventListener"
4981 ], function (method
) {
4982 fakeXhr
[method
] = function () {
4983 return apply(xhr
, method
, arguments
);
4987 var copyAttrs = function (args
) {
4988 each(args
, function (attr
) {
4990 fakeXhr
[attr
] = xhr
[attr
];
4992 if (!IE6Re
.test(navigator
.userAgent
)) {
4999 var stateChange
= function stateChange() {
5000 fakeXhr
.readyState
= xhr
.readyState
;
5001 if (xhr
.readyState
>= FakeXMLHttpRequest
.HEADERS_RECEIVED
) {
5002 copyAttrs(["status", "statusText"]);
5004 if (xhr
.readyState
>= FakeXMLHttpRequest
.LOADING
) {
5005 copyAttrs(["responseText", "response"]);
5007 if (xhr
.readyState
=== FakeXMLHttpRequest
.DONE
) {
5008 copyAttrs(["responseXML"]);
5010 if (fakeXhr
.onreadystatechange
) {
5011 fakeXhr
.onreadystatechange
.call(fakeXhr
, { target
: fakeXhr
});
5015 if (xhr
.addEventListener
) {
5016 for (var event
in fakeXhr
.eventListeners
) {
5017 if (fakeXhr
.eventListeners
.hasOwnProperty(event
)) {
5019 /*eslint-disable no-loop-func*/
5020 each(fakeXhr
.eventListeners
[event
], function (handler
) {
5021 xhr
.addEventListener(event
, handler
);
5023 /*eslint-enable no-loop-func*/
5026 xhr
.addEventListener("readystatechange", stateChange
);
5028 xhr
.onreadystatechange
= stateChange
;
5030 apply(xhr
, "open", xhrArgs
);
5032 FakeXMLHttpRequest
.useFilters
= false;
5034 function verifyRequestOpened(xhr
) {
5035 if (xhr
.readyState
!== FakeXMLHttpRequest
.OPENED
) {
5036 throw new Error("INVALID_STATE_ERR - " + xhr
.readyState
);
5040 function verifyRequestSent(xhr
) {
5041 if (xhr
.readyState
=== FakeXMLHttpRequest
.DONE
) {
5042 throw new Error("Request done");
5046 function verifyHeadersReceived(xhr
) {
5047 if (xhr
.async
&& xhr
.readyState
!== FakeXMLHttpRequest
.HEADERS_RECEIVED
) {
5048 throw new Error("No headers received");
5052 function verifyResponseBodyType(body
) {
5053 if (typeof body
!== "string") {
5054 var error
= new Error("Attempted to respond to fake XMLHttpRequest with " +
5055 body
+ ", which is not a string.");
5056 error
.name
= "InvalidBodyException";
5061 function convertToArrayBuffer(body
) {
5062 var buffer
= new ArrayBuffer(body
.length
);
5063 var view
= new Uint8Array(buffer
);
5064 for (var i
= 0; i
< body
.length
; i
++) {
5065 var charCode
= body
.charCodeAt(i
);
5066 if (charCode
>= 256) {
5067 throw new TypeError("arraybuffer or blob responseTypes require binary string, " +
5068 "invalid character " + body
[i
] + " found.");
5075 function isXmlContentType(contentType
) {
5076 return !contentType
|| /(text\/xml)|(application\/xml)|(\+xml)/.test(contentType
);
5079 function convertResponseBody(responseType
, contentType
, body
) {
5080 if (responseType
=== "" || responseType
=== "text") {
5082 } else if (supportsArrayBuffer
&& responseType
=== "arraybuffer") {
5083 return convertToArrayBuffer(body
);
5084 } else if (responseType
=== "json") {
5086 return JSON
.parse(body
);
5088 // Return parsing failure as null
5091 } else if (supportsBlob
&& responseType
=== "blob") {
5092 var blobOptions
= {};
5094 blobOptions
.type
= contentType
;
5096 return new Blob([convertToArrayBuffer(body
)], blobOptions
);
5097 } else if (responseType
=== "document") {
5098 if (isXmlContentType(contentType
)) {
5099 return FakeXMLHttpRequest
.parseXML(body
);
5103 throw new Error("Invalid responseType " + responseType
);
5106 function clearResponse(xhr
) {
5107 if (xhr
.responseType
=== "" || xhr
.responseType
=== "text") {
5108 xhr
.response
= xhr
.responseText
= "";
5110 xhr
.response
= xhr
.responseText
= null;
5112 xhr
.responseXML
= null;
5115 FakeXMLHttpRequest
.parseXML
= function parseXML(text
) {
5116 // Treat empty string as parsing failure
5119 if (typeof DOMParser
!== "undefined") {
5120 var parser
= new DOMParser();
5121 return parser
.parseFromString(text
, "text/xml");
5123 var xmlDoc
= new window
.ActiveXObject("Microsoft.XMLDOM");
5124 xmlDoc
.async
= "false";
5125 xmlDoc
.loadXML(text
);
5128 // Unable to parse XML - no biggie
5135 FakeXMLHttpRequest
.statusCodes
= {
5137 101: "Switching Protocols",
5141 203: "Non-Authoritative Information",
5143 205: "Reset Content",
5144 206: "Partial Content",
5145 207: "Multi-Status",
5146 300: "Multiple Choice",
5147 301: "Moved Permanently",
5150 304: "Not Modified",
5152 307: "Temporary Redirect",
5154 401: "Unauthorized",
5155 402: "Payment Required",
5158 405: "Method Not Allowed",
5159 406: "Not Acceptable",
5160 407: "Proxy Authentication Required",
5161 408: "Request Timeout",
5164 411: "Length Required",
5165 412: "Precondition Failed",
5166 413: "Request Entity Too Large",
5167 414: "Request-URI Too Long",
5168 415: "Unsupported Media Type",
5169 416: "Requested Range Not Satisfiable",
5170 417: "Expectation Failed",
5171 422: "Unprocessable Entity",
5172 500: "Internal Server Error",
5173 501: "Not Implemented",
5175 503: "Service Unavailable",
5176 504: "Gateway Timeout",
5177 505: "HTTP Version Not Supported"
5180 function makeApi(sinon
) {
5181 sinon
.xhr
= sinonXhr
;
5183 sinon
.extend(FakeXMLHttpRequest
.prototype, sinon
.EventTarget
, {
5186 open
: function open(method
, url
, async
, username
, password
) {
5187 this.method
= method
;
5189 this.async
= typeof async
=== "boolean" ? async
: true;
5190 this.username
= username
;
5191 this.password
= password
;
5192 clearResponse(this);
5193 this.requestHeaders
= {};
5194 this.sendFlag
= false;
5196 if (FakeXMLHttpRequest
.useFilters
=== true) {
5197 var xhrArgs
= arguments
;
5198 var defake
= some(FakeXMLHttpRequest
.filters
, function (filter
) {
5199 return filter
.apply(this, xhrArgs
);
5202 return FakeXMLHttpRequest
.defake(this, arguments
);
5205 this.readyStateChange(FakeXMLHttpRequest
.OPENED
);
5208 readyStateChange
: function readyStateChange(state
) {
5209 this.readyState
= state
;
5211 var readyStateChangeEvent
= new sinon
.Event("readystatechange", false, false, this);
5213 if (typeof this.onreadystatechange
=== "function") {
5215 this.onreadystatechange(readyStateChangeEvent
);
5217 sinon
.logError("Fake XHR onreadystatechange handler", e
);
5221 switch (this.readyState
) {
5222 case FakeXMLHttpRequest
.DONE
:
5223 if (supportsProgress
) {
5224 this.upload
.dispatchEvent(new sinon
.ProgressEvent("progress", {loaded
: 100, total
: 100}));
5225 this.dispatchEvent(new sinon
.ProgressEvent("progress", {loaded
: 100, total
: 100}));
5227 this.upload
.dispatchEvent(new sinon
.Event("load", false, false, this));
5228 this.dispatchEvent(new sinon
.Event("load", false, false, this));
5229 this.dispatchEvent(new sinon
.Event("loadend", false, false, this));
5233 this.dispatchEvent(readyStateChangeEvent
);
5236 setRequestHeader
: function setRequestHeader(header
, value
) {
5239 if (unsafeHeaders
[header
] || /^(Sec-|Proxy-)/.test(header
)) {
5240 throw new Error("Refused to set unsafe header \"" + header
+ "\"");
5243 if (this.requestHeaders
[header
]) {
5244 this.requestHeaders
[header
] += "," + value
;
5246 this.requestHeaders
[header
] = value
;
5251 setResponseHeaders
: function setResponseHeaders(headers
) {
5252 verifyRequestOpened(this);
5253 this.responseHeaders
= {};
5255 for (var header
in headers
) {
5256 if (headers
.hasOwnProperty(header
)) {
5257 this.responseHeaders
[header
] = headers
[header
];
5262 this.readyStateChange(FakeXMLHttpRequest
.HEADERS_RECEIVED
);
5264 this.readyState
= FakeXMLHttpRequest
.HEADERS_RECEIVED
;
5268 // Currently treats ALL data as a DOMString (i.e. no Document)
5269 send
: function send(data
) {
5272 if (!/^(get|head)$/i.test(this.method
)) {
5273 var contentType
= getHeader(this.requestHeaders
, "Content-Type");
5274 if (this.requestHeaders
[contentType
]) {
5275 var value
= this.requestHeaders
[contentType
].split(";");
5276 this.requestHeaders
[contentType
] = value
[0] + ";charset=utf-8";
5277 } else if (supportsFormData
&& !(data
instanceof FormData
)) {
5278 this.requestHeaders
["Content-Type"] = "text/plain;charset=utf-8";
5281 this.requestBody
= data
;
5284 this.errorFlag
= false;
5285 this.sendFlag
= this.async
;
5286 clearResponse(this);
5287 this.readyStateChange(FakeXMLHttpRequest
.OPENED
);
5289 if (typeof this.onSend
=== "function") {
5293 this.dispatchEvent(new sinon
.Event("loadstart", false, false, this));
5296 abort
: function abort() {
5297 this.aborted
= true;
5298 clearResponse(this);
5299 this.errorFlag
= true;
5300 this.requestHeaders
= {};
5301 this.responseHeaders
= {};
5303 if (this.readyState
> FakeXMLHttpRequest
.UNSENT
&& this.sendFlag
) {
5304 this.readyStateChange(FakeXMLHttpRequest
.DONE
);
5305 this.sendFlag
= false;
5308 this.readyState
= FakeXMLHttpRequest
.UNSENT
;
5310 this.dispatchEvent(new sinon
.Event("abort", false, false, this));
5312 this.upload
.dispatchEvent(new sinon
.Event("abort", false, false, this));
5314 if (typeof this.onerror
=== "function") {
5319 getResponseHeader
: function getResponseHeader(header
) {
5320 if (this.readyState
< FakeXMLHttpRequest
.HEADERS_RECEIVED
) {
5324 if (/^Set-Cookie2?$/i.test(header
)) {
5328 header
= getHeader(this.responseHeaders
, header
);
5330 return this.responseHeaders
[header
] || null;
5333 getAllResponseHeaders
: function getAllResponseHeaders() {
5334 if (this.readyState
< FakeXMLHttpRequest
.HEADERS_RECEIVED
) {
5340 for (var header
in this.responseHeaders
) {
5341 if (this.responseHeaders
.hasOwnProperty(header
) &&
5342 !/^Set-Cookie2?$/i.test(header
)) {
5343 headers
+= header
+ ": " + this.responseHeaders
[header
] + "\r\n";
5350 setResponseBody
: function setResponseBody(body
) {
5351 verifyRequestSent(this);
5352 verifyHeadersReceived(this);
5353 verifyResponseBodyType(body
);
5354 var contentType
= this.getResponseHeader("Content-Type");
5356 var isTextResponse
= this.responseType
=== "" || this.responseType
=== "text";
5357 clearResponse(this);
5359 var chunkSize
= this.chunkSize
|| 10;
5363 this.readyStateChange(FakeXMLHttpRequest
.LOADING
);
5365 if (isTextResponse
) {
5366 this.responseText
= this.response
+= body
.substring(index
, index
+ chunkSize
);
5369 } while (index
< body
.length
);
5372 this.response
= convertResponseBody(this.responseType
, contentType
, body
);
5373 if (isTextResponse
) {
5374 this.responseText
= this.response
;
5377 if (this.responseType
=== "document") {
5378 this.responseXML
= this.response
;
5379 } else if (this.responseType
=== "" && isXmlContentType(contentType
)) {
5380 this.responseXML
= FakeXMLHttpRequest
.parseXML(this.responseText
);
5382 this.readyStateChange(FakeXMLHttpRequest
.DONE
);
5385 respond
: function respond(status
, headers
, body
) {
5386 this.status
= typeof status
=== "number" ? status
: 200;
5387 this.statusText
= FakeXMLHttpRequest
.statusCodes
[this.status
];
5388 this.setResponseHeaders(headers
|| {});
5389 this.setResponseBody(body
|| "");
5392 uploadProgress
: function uploadProgress(progressEventRaw
) {
5393 if (supportsProgress
) {
5394 this.upload
.dispatchEvent(new sinon
.ProgressEvent("progress", progressEventRaw
));
5398 downloadProgress
: function downloadProgress(progressEventRaw
) {
5399 if (supportsProgress
) {
5400 this.dispatchEvent(new sinon
.ProgressEvent("progress", progressEventRaw
));
5404 uploadError
: function uploadError(error
) {
5405 if (supportsCustomEvent
) {
5406 this.upload
.dispatchEvent(new sinon
.CustomEvent("error", {detail
: error
}));
5411 sinon
.extend(FakeXMLHttpRequest
, {
5414 HEADERS_RECEIVED
: 2,
5419 sinon
.useFakeXMLHttpRequest = function () {
5420 FakeXMLHttpRequest
.restore
= function restore(keepOnCreate
) {
5421 if (sinonXhr
.supportsXHR
) {
5422 global
.XMLHttpRequest
= sinonXhr
.GlobalXMLHttpRequest
;
5425 if (sinonXhr
.supportsActiveX
) {
5426 global
.ActiveXObject
= sinonXhr
.GlobalActiveXObject
;
5429 delete FakeXMLHttpRequest
.restore
;
5431 if (keepOnCreate
!== true) {
5432 delete FakeXMLHttpRequest
.onCreate
;
5435 if (sinonXhr
.supportsXHR
) {
5436 global
.XMLHttpRequest
= FakeXMLHttpRequest
;
5439 if (sinonXhr
.supportsActiveX
) {
5440 global
.ActiveXObject
= function ActiveXObject(objId
) {
5441 if (objId
=== "Microsoft.XMLHTTP" || /^Msxml2\.XMLHTTP/i.test(objId
)) {
5443 return new FakeXMLHttpRequest();
5446 return new sinonXhr
.GlobalActiveXObject(objId
);
5450 return FakeXMLHttpRequest
;
5453 sinon
.FakeXMLHttpRequest
= FakeXMLHttpRequest
;
5456 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
5457 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
5459 function loadDependencies(require
, exports
, module
) {
5460 var sinon
= require("./core");
5461 require("../extend");
5463 require("../log_error");
5465 module
.exports
= sinon
;
5469 define(loadDependencies
);
5474 loadDependencies(require
, module
.exports
, module
);
5479 makeApi(sinonGlobal
);
5482 typeof sinon
=== "object" && sinon
, // eslint-disable-line no-undef
5483 typeof global
!== "undefined" ? global
: self
5487 * @depend fake_xdomain_request.js
5488 * @depend fake_xml_http_request.js
5489 * @depend ../format.js
5490 * @depend ../log_error.js
5493 * The Sinon "server" mimics a web server that receives requests from
5494 * sinon.FakeXMLHttpRequest and provides an API to respond to those requests,
5495 * both synchronously and asynchronously. To respond synchronuously, canned
5496 * answers have to be provided upfront.
5498 * @author Christian Johansen (christian@cjohansen.no)
5501 * Copyright (c) 2010-2013 Christian Johansen
5507 function responseArray(handler
) {
5508 var response
= handler
;
5510 if (Object
.prototype.toString
.call(handler
) !== "[object Array]") {
5511 response
= [200, {}, handler
];
5514 if (typeof response
[2] !== "string") {
5515 throw new TypeError("Fake server response body should be string, but was " +
5516 typeof response
[2]);
5522 var wloc
= typeof window
!== "undefined" ? window
.location
: {};
5523 var rCurrLoc
= new RegExp("^" + wloc
.protocol
+ "//" + wloc
.host
);
5525 function matchOne(response
, reqMethod
, reqUrl
) {
5526 var rmeth
= response
.method
;
5527 var matchMethod
= !rmeth
|| rmeth
.toLowerCase() === reqMethod
.toLowerCase();
5528 var url
= response
.url
;
5529 var matchUrl
= !url
|| url
=== reqUrl
|| (typeof url
.test
=== "function" && url
.test(reqUrl
));
5531 return matchMethod
&& matchUrl
;
5534 function match(response
, request
) {
5535 var requestUrl
= request
.url
;
5537 if (!/^https?:\/\//.test(requestUrl
) || rCurrLoc
.test(requestUrl
)) {
5538 requestUrl
= requestUrl
.replace(rCurrLoc
, "");
5541 if (matchOne(response
, this.getHTTPMethod(request
), requestUrl
)) {
5542 if (typeof response
.response
=== "function") {
5543 var ru
= response
.url
;
5544 var args
= [request
].concat(ru
&& typeof ru
.exec
=== "function" ? ru
.exec(requestUrl
).slice(1) : []);
5545 return response
.response
.apply(response
, args
);
5554 function makeApi(sinon
) {
5555 sinon
.fakeServer
= {
5556 create: function (config
) {
5557 var server
= sinon
.create(this);
5558 server
.configure(config
);
5559 if (!sinon
.xhr
.supportsCORS
) {
5560 this.xhr
= sinon
.useFakeXDomainRequest();
5562 this.xhr
= sinon
.useFakeXMLHttpRequest();
5564 server
.requests
= [];
5566 this.xhr
.onCreate = function (xhrObj
) {
5567 server
.addRequest(xhrObj
);
5572 configure: function (config
) {
5574 "autoRespond": true,
5575 "autoRespondAfter": true,
5576 "respondImmediately": true,
5577 "fakeHTTPMethods": true
5581 config
= config
|| {};
5582 for (setting
in config
) {
5583 if (whitelist
.hasOwnProperty(setting
) && config
.hasOwnProperty(setting
)) {
5584 this[setting
] = config
[setting
];
5588 addRequest
: function addRequest(xhrObj
) {
5590 push
.call(this.requests
, xhrObj
);
5592 xhrObj
.onSend = function () {
5593 server
.handleRequest(this);
5595 if (server
.respondImmediately
) {
5597 } else if (server
.autoRespond
&& !server
.responding
) {
5598 setTimeout(function () {
5599 server
.responding
= false;
5601 }, server
.autoRespondAfter
|| 10);
5603 server
.responding
= true;
5608 getHTTPMethod
: function getHTTPMethod(request
) {
5609 if (this.fakeHTTPMethods
&& /post/i.test(request
.method
)) {
5610 var matches
= (request
.requestBody
|| "").match(/_method=([^\b;]+)/);
5611 return matches
? matches
[1] : request
.method
;
5614 return request
.method
;
5617 handleRequest
: function handleRequest(xhr
) {
5623 push
.call(this.queue
, xhr
);
5625 this.processRequest(xhr
);
5629 log
: function log(response
, request
) {
5632 str
= "Request:\n" + sinon
.format(request
) + "\n\n";
5633 str
+= "Response:\n" + sinon
.format(response
) + "\n\n";
5638 respondWith
: function respondWith(method
, url
, body
) {
5639 if (arguments
.length
=== 1 && typeof method
!== "function") {
5640 this.response
= responseArray(method
);
5644 if (!this.responses
) {
5645 this.responses
= [];
5648 if (arguments
.length
=== 1) {
5650 url
= method
= null;
5653 if (arguments
.length
=== 2) {
5659 push
.call(this.responses
, {
5662 response
: typeof body
=== "function" ? body
: responseArray(body
)
5666 respond
: function respond() {
5667 if (arguments
.length
> 0) {
5668 this.respondWith
.apply(this, arguments
);
5671 var queue
= this.queue
|| [];
5672 var requests
= queue
.splice(0, queue
.length
);
5674 for (var i
= 0; i
< requests
.length
; i
++) {
5675 this.processRequest(requests
[i
]);
5679 processRequest
: function processRequest(request
) {
5681 if (request
.aborted
) {
5685 var response
= this.response
|| [404, {}, ""];
5687 if (this.responses
) {
5688 for (var l
= this.responses
.length
, i
= l
- 1; i
>= 0; i
--) {
5689 if (match
.call(this, this.responses
[i
], request
)) {
5690 response
= this.responses
[i
].response
;
5696 if (request
.readyState
!== 4) {
5697 this.log(response
, request
);
5699 request
.respond(response
[0], response
[1], response
[2]);
5702 sinon
.logError("Fake server request processing", e
);
5706 restore
: function restore() {
5707 return this.xhr
.restore
&& this.xhr
.restore
.apply(this.xhr
, arguments
);
5712 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
5713 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
5715 function loadDependencies(require
, exports
, module
) {
5716 var sinon
= require("./core");
5717 require("./fake_xdomain_request");
5718 require("./fake_xml_http_request");
5719 require("../format");
5721 module
.exports
= sinon
;
5725 define(loadDependencies
);
5726 } else if (isNode
) {
5727 loadDependencies(require
, module
.exports
, module
);
5729 makeApi(sinon
); // eslint-disable-line no-undef
5734 * @depend fake_server.js
5735 * @depend fake_timers.js
5738 * Add-on for sinon.fakeServer that automatically handles a fake timer along with
5739 * the FakeXMLHttpRequest. The direct inspiration for this add-on is jQuery
5740 * 1.3.x, which does not use xhr object's onreadystatehandler at all - instead,
5741 * it polls the object for completion with setInterval. Dispite the direct
5742 * motivation, there is nothing jQuery-specific in this file, so it can be used
5743 * in any environment where the ajax implementation depends on setInterval or
5746 * @author Christian Johansen (christian@cjohansen.no)
5749 * Copyright (c) 2010-2013 Christian Johansen
5753 function makeApi(sinon
) {
5754 function Server() {}
5755 Server
.prototype = sinon
.fakeServer
;
5757 sinon
.fakeServerWithClock
= new Server();
5759 sinon
.fakeServerWithClock
.addRequest
= function addRequest(xhr
) {
5761 if (typeof setTimeout
.clock
=== "object") {
5762 this.clock
= setTimeout
.clock
;
5764 this.clock
= sinon
.useFakeTimers();
5765 this.resetClock
= true;
5768 if (!this.longestTimeout
) {
5769 var clockSetTimeout
= this.clock
.setTimeout
;
5770 var clockSetInterval
= this.clock
.setInterval
;
5773 this.clock
.setTimeout = function (fn
, timeout
) {
5774 server
.longestTimeout
= Math
.max(timeout
, server
.longestTimeout
|| 0);
5776 return clockSetTimeout
.apply(this, arguments
);
5779 this.clock
.setInterval = function (fn
, timeout
) {
5780 server
.longestTimeout
= Math
.max(timeout
, server
.longestTimeout
|| 0);
5782 return clockSetInterval
.apply(this, arguments
);
5787 return sinon
.fakeServer
.addRequest
.call(this, xhr
);
5790 sinon
.fakeServerWithClock
.respond
= function respond() {
5791 var returnVal
= sinon
.fakeServer
.respond
.apply(this, arguments
);
5794 this.clock
.tick(this.longestTimeout
|| 0);
5795 this.longestTimeout
= 0;
5797 if (this.resetClock
) {
5798 this.clock
.restore();
5799 this.resetClock
= false;
5806 sinon
.fakeServerWithClock
.restore
= function restore() {
5808 this.clock
.restore();
5811 return sinon
.fakeServer
.restore
.apply(this, arguments
);
5815 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
5816 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
5818 function loadDependencies(require
) {
5819 var sinon
= require("./core");
5820 require("./fake_server");
5821 require("./fake_timers");
5826 define(loadDependencies
);
5827 } else if (isNode
) {
5828 loadDependencies(require
);
5830 makeApi(sinon
); // eslint-disable-line no-undef
5835 * @depend util/core.js
5837 * @depend collection.js
5838 * @depend util/fake_timers.js
5839 * @depend util/fake_server_with_clock.js
5842 * Manages fake collections as well as fake utilities such as Sinon's
5843 * timers and fake XHR implementation in one convenient object.
5845 * @author Christian Johansen (christian@cjohansen.no)
5848 * Copyright (c) 2010-2013 Christian Johansen
5850 (function (sinonGlobal
) {
5852 function makeApi(sinon
) {
5855 function exposeValue(sandbox
, config
, key
, value
) {
5860 if (config
.injectInto
&& !(key
in config
.injectInto
)) {
5861 config
.injectInto
[key
] = value
;
5862 sandbox
.injectedKeys
.push(key
);
5864 push
.call(sandbox
.args
, value
);
5868 function prepareSandboxFromConfig(config
) {
5869 var sandbox
= sinon
.create(sinon
.sandbox
);
5871 if (config
.useFakeServer
) {
5872 if (typeof config
.useFakeServer
=== "object") {
5873 sandbox
.serverPrototype
= config
.useFakeServer
;
5876 sandbox
.useFakeServer();
5879 if (config
.useFakeTimers
) {
5880 if (typeof config
.useFakeTimers
=== "object") {
5881 sandbox
.useFakeTimers
.apply(sandbox
, config
.useFakeTimers
);
5883 sandbox
.useFakeTimers();
5890 sinon
.sandbox
= sinon
.extend(sinon
.create(sinon
.collection
), {
5891 useFakeTimers
: function useFakeTimers() {
5892 this.clock
= sinon
.useFakeTimers
.apply(sinon
, arguments
);
5894 return this.add(this.clock
);
5897 serverPrototype
: sinon
.fakeServer
,
5899 useFakeServer
: function useFakeServer() {
5900 var proto
= this.serverPrototype
|| sinon
.fakeServer
;
5902 if (!proto
|| !proto
.create
) {
5906 this.server
= proto
.create();
5907 return this.add(this.server
);
5910 inject: function (obj
) {
5911 sinon
.collection
.inject
.call(this, obj
);
5914 obj
.clock
= this.clock
;
5918 obj
.server
= this.server
;
5919 obj
.requests
= this.server
.requests
;
5922 obj
.match
= sinon
.match
;
5927 restore: function () {
5928 sinon
.collection
.restore
.apply(this, arguments
);
5929 this.restoreContext();
5932 restoreContext: function () {
5933 if (this.injectedKeys
) {
5934 for (var i
= 0, j
= this.injectedKeys
.length
; i
< j
; i
++) {
5935 delete this.injectInto
[this.injectedKeys
[i
]];
5937 this.injectedKeys
= [];
5941 create: function (config
) {
5943 return sinon
.create(sinon
.sandbox
);
5946 var sandbox
= prepareSandboxFromConfig(config
);
5947 sandbox
.args
= sandbox
.args
|| [];
5948 sandbox
.injectedKeys
= [];
5949 sandbox
.injectInto
= config
.injectInto
;
5952 var exposed
= sandbox
.inject({});
5954 if (config
.properties
) {
5955 for (var i
= 0, l
= config
.properties
.length
; i
< l
; i
++) {
5956 prop
= config
.properties
[i
];
5957 value
= exposed
[prop
] || prop
=== "sandbox" && sandbox
;
5958 exposeValue(sandbox
, config
, prop
, value
);
5961 exposeValue(sandbox
, config
, "sandbox", value
);
5970 sinon
.sandbox
.useFakeXMLHttpRequest
= sinon
.sandbox
.useFakeServer
;
5972 return sinon
.sandbox
;
5975 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
5976 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
5978 function loadDependencies(require
, exports
, module
) {
5979 var sinon
= require("./util/core");
5980 require("./extend");
5981 require("./util/fake_server_with_clock");
5982 require("./util/fake_timers");
5983 require("./collection");
5984 module
.exports
= makeApi(sinon
);
5988 define(loadDependencies
);
5993 loadDependencies(require
, module
.exports
, module
);
5998 makeApi(sinonGlobal
);
6001 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
6005 * @depend util/core.js
6006 * @depend sandbox.js
6009 * Test function, sandboxes fakes
6011 * @author Christian Johansen (christian@cjohansen.no)
6014 * Copyright (c) 2010-2013 Christian Johansen
6016 (function (sinonGlobal
) {
6018 function makeApi(sinon
) {
6019 var slice
= Array
.prototype.slice
;
6021 function test(callback
) {
6022 var type
= typeof callback
;
6024 if (type
!== "function") {
6025 throw new TypeError("sinon.test needs to wrap a test function, got " + type
);
6028 function sinonSandboxedTest() {
6029 var config
= sinon
.getConfig(sinon
.config
);
6030 config
.injectInto
= config
.injectIntoThis
&& this || config
.injectInto
;
6031 var sandbox
= sinon
.sandbox
.create(config
);
6032 var args
= slice
.call(arguments
);
6033 var oldDone
= args
.length
&& args
[args
.length
- 1];
6034 var exception
, result
;
6036 if (typeof oldDone
=== "function") {
6037 args
[args
.length
- 1] = function sinonDone(res
) {
6041 sandbox
.verifyAndRestore();
6048 result
= callback
.apply(this, args
.concat(sandbox
.args
));
6053 if (typeof oldDone
!== "function") {
6054 if (typeof exception
!== "undefined") {
6058 sandbox
.verifyAndRestore();
6065 if (callback
.length
) {
6066 return function sinonAsyncSandboxedTest(done
) { // eslint-disable-line no-unused-vars
6067 return sinonSandboxedTest
.apply(this, arguments
);
6071 return sinonSandboxedTest
;
6075 injectIntoThis
: true,
6077 properties
: ["spy", "stub", "mock", "clock", "server", "requests"],
6078 useFakeTimers
: true,
6086 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
6087 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
6089 function loadDependencies(require
, exports
, module
) {
6090 var core
= require("./util/core");
6091 require("./sandbox");
6092 module
.exports
= makeApi(core
);
6096 define(loadDependencies
);
6097 } else if (isNode
) {
6098 loadDependencies(require
, module
.exports
, module
);
6099 } else if (sinonGlobal
) {
6100 makeApi(sinonGlobal
);
6102 }(typeof sinon
=== "object" && sinon
|| null)); // eslint-disable-line no-undef
6105 * @depend util/core.js
6109 * Test case, sandboxes all test functions
6111 * @author Christian Johansen (christian@cjohansen.no)
6114 * Copyright (c) 2010-2013 Christian Johansen
6116 (function (sinonGlobal
) {
6118 function createTest(property
, setUp
, tearDown
) {
6119 return function () {
6121 setUp
.apply(this, arguments
);
6124 var exception
, result
;
6127 result
= property
.apply(this, arguments
);
6133 tearDown
.apply(this, arguments
);
6144 function makeApi(sinon
) {
6145 function testCase(tests
, prefix
) {
6146 if (!tests
|| typeof tests
!== "object") {
6147 throw new TypeError("sinon.testCase needs an object with test functions");
6150 prefix
= prefix
|| "test";
6151 var rPrefix
= new RegExp("^" + prefix
);
6153 var setUp
= tests
.setUp
;
6154 var tearDown
= tests
.tearDown
;
6159 for (testName
in tests
) {
6160 if (tests
.hasOwnProperty(testName
) && !/^(setUp|tearDown)$/.test(testName
)) {
6161 property
= tests
[testName
];
6163 if (typeof property
=== "function" && rPrefix
.test(testName
)) {
6166 if (setUp
|| tearDown
) {
6167 method
= createTest(property
, setUp
, tearDown
);
6170 methods
[testName
] = sinon
.test(method
);
6172 methods
[testName
] = tests
[testName
];
6180 sinon
.testCase
= testCase
;
6184 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
6185 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
6187 function loadDependencies(require
, exports
, module
) {
6188 var core
= require("./util/core");
6190 module
.exports
= makeApi(core
);
6194 define(loadDependencies
);
6199 loadDependencies(require
, module
.exports
, module
);
6204 makeApi(sinonGlobal
);
6207 typeof sinon
=== "object" && sinon
// eslint-disable-line no-undef
6211 * @depend times_in_words.js
6212 * @depend util/core.js
6217 * Assertions matching the test spy retrieval interface.
6219 * @author Christian Johansen (christian@cjohansen.no)
6222 * Copyright (c) 2010-2013 Christian Johansen
6224 (function (sinonGlobal
, global
) {
6226 var slice
= Array
.prototype.slice
;
6228 function makeApi(sinon
) {
6231 function verifyIsStub() {
6234 for (var i
= 0, l
= arguments
.length
; i
< l
; ++i
) {
6235 method
= arguments
[i
];
6238 assert
.fail("fake is not a spy");
6241 if (method
.proxy
&& method
.proxy
.isSinonProxy
) {
6242 verifyIsStub(method
.proxy
);
6244 if (typeof method
!== "function") {
6245 assert
.fail(method
+ " is not a function");
6248 if (typeof method
.getCall
!== "function") {
6249 assert
.fail(method
+ " is not stubbed");
6256 function failAssertion(object
, msg
) {
6257 object
= object
|| global
;
6258 var failMethod
= object
.fail
|| assert
.fail
;
6259 failMethod
.call(object
, msg
);
6262 function mirrorPropAsAssertion(name
, method
, message
) {
6263 if (arguments
.length
=== 2) {
6268 assert
[name
] = function (fake
) {
6271 var args
= slice
.call(arguments
, 1);
6274 if (typeof method
=== "function") {
6275 failed
= !method(fake
);
6277 failed
= typeof fake
[method
] === "function" ?
6278 !fake
[method
].apply(fake
, args
) : !fake
[method
];
6282 failAssertion(this, (fake
.printf
|| fake
.proxy
.printf
).apply(fake
, [message
].concat(args
)));
6289 function exposedName(prefix
, prop
) {
6290 return !prefix
|| /^fail/.test(prop
) ? prop
:
6291 prefix
+ prop
.slice(0, 1).toUpperCase() + prop
.slice(1);
6295 failException
: "AssertError",
6297 fail
: function fail(message
) {
6298 var error
= new Error(message
);
6299 error
.name
= this.failException
|| assert
.failException
;
6304 pass
: function pass() {},
6306 callOrder
: function assertCallOrder() {
6307 verifyIsStub
.apply(null, arguments
);
6311 if (!sinon
.calledInOrder(arguments
)) {
6313 expected
= [].join
.call(arguments
, ", ");
6314 var calls
= slice
.call(arguments
);
6315 var i
= calls
.length
;
6317 if (!calls
[--i
].called
) {
6321 actual
= sinon
.orderByFirstCall(calls
).join(", ");
6323 // If this fails, we'll just fall back to the blank string
6326 failAssertion(this, "expected " + expected
+ " to be " +
6327 "called in order but were called as " + actual
);
6329 assert
.pass("callOrder");
6333 callCount
: function assertCallCount(method
, count
) {
6334 verifyIsStub(method
);
6336 if (method
.callCount
!== count
) {
6337 var msg
= "expected %n to be called " + sinon
.timesInWords(count
) +
6338 " but was called %c%C";
6339 failAssertion(this, method
.printf(msg
));
6341 assert
.pass("callCount");
6345 expose
: function expose(target
, options
) {
6347 throw new TypeError("target is null or undefined");
6350 var o
= options
|| {};
6351 var prefix
= typeof o
.prefix
=== "undefined" && "assert" || o
.prefix
;
6352 var includeFail
= typeof o
.includeFail
=== "undefined" || !!o
.includeFail
;
6354 for (var method
in this) {
6355 if (method
!== "expose" && (includeFail
|| !/^(fail)/.test(method
))) {
6356 target
[exposedName(prefix
, method
)] = this[method
];
6363 match
: function match(actual
, expectation
) {
6364 var matcher
= sinon
.match(expectation
);
6365 if (matcher
.test(actual
)) {
6366 assert
.pass("match");
6369 "expected value to match",
6370 " expected = " + sinon
.format(expectation
),
6371 " actual = " + sinon
.format(actual
)
6374 failAssertion(this, formatted
.join("\n"));
6379 mirrorPropAsAssertion("called", "expected %n to have been called at least once but was never called");
6380 mirrorPropAsAssertion("notCalled", function (spy
) {
6382 }, "expected %n to not have been called but was called %c%C");
6383 mirrorPropAsAssertion("calledOnce", "expected %n to be called once but was called %c%C");
6384 mirrorPropAsAssertion("calledTwice", "expected %n to be called twice but was called %c%C");
6385 mirrorPropAsAssertion("calledThrice", "expected %n to be called thrice but was called %c%C");
6386 mirrorPropAsAssertion("calledOn", "expected %n to be called with %1 as this but was called with %t");
6387 mirrorPropAsAssertion(
6389 "expected %n to always be called with %1 as this but was called with %t"
6391 mirrorPropAsAssertion("calledWithNew", "expected %n to be called with new");
6392 mirrorPropAsAssertion("alwaysCalledWithNew", "expected %n to always be called with new");
6393 mirrorPropAsAssertion("calledWith", "expected %n to be called with arguments %*%C");
6394 mirrorPropAsAssertion("calledWithMatch", "expected %n to be called with match %*%C");
6395 mirrorPropAsAssertion("alwaysCalledWith", "expected %n to always be called with arguments %*%C");
6396 mirrorPropAsAssertion("alwaysCalledWithMatch", "expected %n to always be called with match %*%C");
6397 mirrorPropAsAssertion("calledWithExactly", "expected %n to be called with exact arguments %*%C");
6398 mirrorPropAsAssertion("alwaysCalledWithExactly", "expected %n to always be called with exact arguments %*%C");
6399 mirrorPropAsAssertion("neverCalledWith", "expected %n to never be called with arguments %*%C");
6400 mirrorPropAsAssertion("neverCalledWithMatch", "expected %n to never be called with match %*%C");
6401 mirrorPropAsAssertion("threw", "%n did not throw exception%C");
6402 mirrorPropAsAssertion("alwaysThrew", "%n did not always throw exception%C");
6404 sinon
.assert
= assert
;
6408 var isNode
= typeof module
!== "undefined" && module
.exports
&& typeof require
=== "function";
6409 var isAMD
= typeof define
=== "function" && typeof define
.amd
=== "object" && define
.amd
;
6411 function loadDependencies(require
, exports
, module
) {
6412 var sinon
= require("./util/core");
6414 require("./format");
6415 module
.exports
= makeApi(sinon
);
6419 define(loadDependencies
);
6424 loadDependencies(require
, module
.exports
, module
);
6429 makeApi(sinonGlobal
);
6432 typeof sinon
=== "object" && sinon
, // eslint-disable-line no-undef
6433 typeof global
!== "undefined" ? global
: self