Socket
Socket
Sign inDemoInstall

sinon

Package Overview
Dependencies
Maintainers
0
Versions
208
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

sinon - npm Package Compare versions

Comparing version 1.0.2 to 1.1.0

.gitignore

33

Changelog.txt

@@ -0,1 +1,34 @@

== 1.1.0 / 2011-05-04
* The fake server now has a autoRespond method which allows it to respond to
requests on the fly (asynchronously), making it a good fit for mockup
development
* Stubs and spies now has a withArgs method. Using it allows you to create
several spies/stubs for the same method, filtered by received arguments
* Stubs now has yields and yieldsTo methods for fuzzily invoking callbacks.
They work like callsArgAt only by inferring what callback to invoke, and
yieldsTo can invoke callbacks in object "options" arguments.
* Allow sandboxes/collections to stub any property so long as the object
has the property as an own property
* Significantly improve error reporting from failed mock expecations. Now prints
all met and unmet expectations with expected and received arguments
* Allow mock expectations to be consumed in any order
* Add pretty printing of all calls when assertions fail
* Fix bug: Stub exception message ended up as "undefined" (string) if not
specified
* Pass capture groups in URLs to fakeServer function handlers
* Pass through return value from test function in testCase
* typeof require is not enough to assume node, also use typeof module
* Don't use Object.create in sinon.create. In the off chance that someone stubs
it, sinon will fail mysteriously (Thanks to Espen Dalløkken)
* Catch exceptions when parsing DOM elements "on a hunch"
When responding to XHRs, Sinon acts like most browsers and try to parse the
response into responseXML if Content-Type indicates XML or HTML. However, it
also does this if the type is not set. Obviously, this may misfire and
should be caught.
* Fix fakeServer.respond() to not drop requests when they are queued during the
processing of an existing queue. (Sven Fuchs)
* Clean up module loading in CommonJS environments (Node.js still the only
tested such environment). No longer (temporarily) modifies require.paths,
always loads all modules.
== 1.0.2 / 2011-02-22

@@ -2,0 +35,0 @@ * Fix JSON bug in package.json

53

lib/sinon.js

@@ -11,2 +11,4 @@ /*jslint eqeqeq: false, onevar: false, forin: true, nomen: false, regexp: false, plusplus: false*/

*/
"use strict";
var sinon = (function () {

@@ -16,10 +18,16 @@ var div = typeof document != "undefined" && document.createElement("div");

function isNode(obj) {
var success = false;
try {
div.appendChild(obj);
div.removeChild(obj);
obj.appendChild(div);
success = div.parentNode == obj;
} catch (e) {
return false;
} finally {
try {
obj.removeChild(div);
} catch (e) {}
}
return true;
return success;
}

@@ -76,2 +84,8 @@

}
// DONT ENUM bug, only care about toString
if (arguments[i].hasOwnProperty("toString") &&
arguments[i].toString != target.toString) {
target.toString = arguments[i].toString;
}
}

@@ -84,9 +98,5 @@ }

create: function create(proto) {
if (Object.create) {
return Object.create(proto);
} else {
var F = function () {};
F.prototype = proto;
return new F();
}
var F = function () {};
F.prototype = proto;
return new F();
},

@@ -201,2 +211,6 @@

format: function (val) {
return "" + val;
},
defaultConfig: {

@@ -213,13 +227,12 @@ injectIntoThis: true,

if (typeof module == "object" && typeof require == "function") {
require.paths.unshift(__dirname);
module.exports = sinon;
module.exports.spy = require("sinon/spy");
module.exports.stub = require("sinon/stub");
module.exports.mock = require("sinon/mock");
module.exports.collection = require("sinon/collection");
module.exports.assert = require("sinon/assert");
module.exports.sandbox = require("sinon/sandbox");
module.exports.test = require("sinon/test");
module.exports.testCase = require("sinon/test_case");
require.paths.shift();
module.exports.spy = require("./sinon/spy");
module.exports.stub = require("./sinon/stub");
module.exports.mock = require("./sinon/mock");
module.exports.collection = require("./sinon/collection");
module.exports.assert = require("./sinon/assert");
module.exports.sandbox = require("./sinon/sandbox");
module.exports.test = require("./sinon/test");
module.exports.testCase = require("./sinon/test_case");
module.exports.assert = require("./sinon/assert");
}

@@ -15,2 +15,4 @@ /**

*/
"use strict";
(function (sinon) {

@@ -65,2 +67,11 @@ var commonJSModule = typeof module == "object" && typeof require == "function";

msg = msg.replace("%n", fake + "");
msg = msg.replace("%C", function (m) {
return formatSpyCalls(fake);
});
msg = msg.replace("%t", function (m) {
return formatThisValues(fake);
});
msg = msg.replace("%*", [].slice.call(arguments, 1).join(", "));

@@ -79,2 +90,22 @@

function formatSpyCalls(spy) {
var calls = [];
for (var i = 0, l = spy.callCount; i < l; ++i) {
calls.push(" " + spy.getCall(i).toString());
}
return calls.length > 0 ? "\n" + calls.join("\n") : "";
}
function formatThisValues(spy) {
var objects = [];
for (var i = 0, l = spy.callCount; i < l; ++i) {
objects.push(sinon.format(spy.thisValues[i]));
}
return objects.join(", ");
}
assert = {

@@ -107,4 +138,5 @@ failException: "AssertError",

if (method.called) {
failAssertion(this, "expected " + method + " to not have been called " +
"but was called " + times(method.callCount));
failAssertion(
this, "expected " + method + " to not have been called but was " +
"called " + times(method.callCount) + formatSpyCalls(method));
} else {

@@ -158,4 +190,5 @@ assert.pass("notCalled");

if (method.callCount != count) {
failAssertion(this, "expected " + method + " to be called " + times(count) +
" but was called " + times(method.callCount));
failAssertion(this, "expected " + method + " to be called " +
times(count) + " but was called " +
times(method.callCount) + formatSpyCalls(method));
} else {

@@ -197,13 +230,13 @@ assert.pass("callCount");

mirrorAssertion("calledOnce", "expected %n to be called once but was called %c");
mirrorAssertion("calledTwice", "expected %n to be called twice but was called %c");
mirrorAssertion("calledThrice", "expected %n to be called thrice but was called %c");
mirrorAssertion("calledOn", "expected %n to be called with %1 as this");
mirrorAssertion("alwaysCalledOn", "expected %n to always be called with %1 as this");
mirrorAssertion("calledWith", "expected %n to be called with arguments %*");
mirrorAssertion("alwaysCalledWith", "expected %n to always be called with arguments %*");
mirrorAssertion("calledWithExactly", "expected %n to be called with exact arguments %*");
mirrorAssertion("alwaysCalledWithExactly", "expected %n to always be called with exact arguments %*");
mirrorAssertion("threw", "%n did not throw exception");
mirrorAssertion("alwaysThrew", "%n did not always throw exception");
mirrorAssertion("calledOnce", "expected %n to be called once but was called %c%C");
mirrorAssertion("calledTwice", "expected %n to be called twice but was called %c%C");
mirrorAssertion("calledThrice", "expected %n to be called thrice but was called %c%C");
mirrorAssertion("calledOn", "expected %n to be called with %1 as this but was called with %t");
mirrorAssertion("alwaysCalledOn", "expected %n to always be called with %1 as this but was called with %t");
mirrorAssertion("calledWith", "expected %n to be called with arguments %*%C");
mirrorAssertion("alwaysCalledWith", "expected %n to always be called with arguments %*%C");
mirrorAssertion("calledWithExactly", "expected %n to be called with exact arguments %*%C");
mirrorAssertion("alwaysCalledWithExactly", "expected %n to always be called with exact arguments %*%C");
mirrorAssertion("threw", "%n did not throw exception%C");
mirrorAssertion("alwaysThrew", "%n did not always throw exception%C");

@@ -210,0 +243,0 @@ if (commonJSModule) {

@@ -16,2 +16,4 @@ /**

*/
"use strict";
(function (sinon) {

@@ -81,3 +83,21 @@ var commonJSModule = typeof module == "object" && typeof require == "function";

stub: function stub() {
stub: function stub(object, property, value) {
if (property) {
var original = object[property];
if (typeof original != "function") {
if (!object.hasOwnProperty(property)) {
throw new TypeError("Cannot stub non-existent own property " + property);
}
object[property] = value;
return this.add({
restore: function () {
object[property] = original;
}
});
}
}
return this.add(sinon.stub.apply(sinon, arguments));

@@ -84,0 +104,0 @@ },

@@ -15,2 +15,4 @@ /**

*/
"use strict";
(function (sinon) {

@@ -100,18 +102,18 @@ var commonJSModule = typeof module == "object" && typeof require == "function";

var expectations = this.expectations || {};
var exception;
var messages = [], met = [];
try {
each(this.proxies, function (proxy) {
each(expectations[proxy], function (expectation) {
expectation.verify();
});
each(this.proxies, function (proxy) {
each(expectations[proxy], function (expectation) {
if (!expectation.met()) {
messages.push(expectation.toString());
} else {
met.push(expectation.toString());
}
});
} catch (e) {
exception = e;
}
});
this.restore();
if (exception) {
throw exception;
if (messages.length > 0) {
err(messages.concat(met).join("\n"));
}

@@ -127,3 +129,4 @@

for (var i = 0; i < length; i += 1) {
if (!expectations[i].met()) {
if (!expectations[i].met() &&
expectations[i].allowsCall(thisValue, args)) {
return expectations[i].apply(thisValue, args);

@@ -133,3 +136,14 @@ }

return expectations[length - 1].apply(thisValue, args);
var messages = [];
for (i = 0; i < length; i += 1) {
messages.push(" " + expectations[i].toString());
}
messages.unshift("Unexpected call: " + sinon.spyCall.toString.call({
proxy: method,
args: args
}));
err(messages.join("\n"));
}

@@ -151,3 +165,5 @@ };

function timesInWords(times) {
if (times == 1) {
if (times == 0) {
return "never";
} else if (times == 1) {
return "once";

@@ -163,2 +179,31 @@ } else if (times == 2) {

function callCountInWords(callCount) {
if (callCount == 0) {
return "never called";
} else {
return "called " + timesInWords(callCount);
}
}
function expectedCallCountInWords(expectation) {
var min = expectation.minCalls;
var max = expectation.maxCalls;
if (typeof min == "number" && typeof max == "number") {
var str = timesInWords(min);
if (min != max) {
str = "at least " + str + " and at most " + timesInWords(max);
}
return str;
}
if (typeof min == "number") {
return "at least " + timesInWords(min);
}
return "at most " + timesInWords(max);
}
function receivedMinCalls(expectation) {

@@ -293,2 +338,35 @@ var hasMinLimit = typeof expectation.minCalls == "number";

allowsCall: function allowsCall(thisValue, args) {
if (this.met()) {
return false;
}
if ("expectedThis" in this && this.expectedThis !== thisValue) {
return false;
}
if (!("expectedArguments" in this)) {
return true;
}
args = args || [];
if (args.length < this.expectedArguments.length) {
return false;
}
if (this.expectsExactArgCount &&
args.length != this.expectedArguments.length) {
return false;
}
for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) {
if (!sinon.deepEqual(this.expectedArguments[i], args[i])) {
return false;
}
}
return true;
},
withArgs: function withArgs() {

@@ -310,6 +388,27 @@ this.expectedArguments = slice.call(arguments);

toString: function () {
var args = (this.expectedArguments || []).slice();
if (!this.expectsExactArgCount) {
args.push("[...]");
}
var callStr = sinon.spyCall.toString.call({
proxy: this.method, args: args
});
var message = callStr.replace(", [...", "[, ...") + " " +
expectedCallCountInWords(this);
if (this.met()) {
return "Expectation met: " + message;
}
return "Expected " + message + " (" +
callCountInWords(this.callCount) + ")";
},
verify: function verify() {
if (!this.met()) {
err(this.method + " expected to be called " + timesInWords(this.minCalls) +
", but was called " + timesInWords(this.callCount));
err(this.toString());
}

@@ -316,0 +415,0 @@

@@ -18,5 +18,7 @@ /**

*/
if (typeof require == "function") {
"use strict";
if (typeof module == "object" && typeof require == "function") {
var sinon = require("sinon");
sinon.extend(sinon, require("sinon/util/fake_timers"));
sinon.extend(sinon, require("./util/fake_timers"));
}

@@ -23,0 +25,0 @@

@@ -12,2 +12,4 @@ /* @depend ../sinon.js */

*/
"use strict";
(function (sinon) {

@@ -67,9 +69,32 @@ var commonJSModule = typeof module == "object" && typeof require == "function";

function matchingFake(fakes, args, strict) {
if (!fakes) {
return;
}
var alen = args.length;
for (var i = 0, l = fakes.length; i < l; i++) {
if (fakes[i].matches(args, strict)) {
return fakes[i];
}
}
}
var uuid = 0;
// Public API
var spyApi = {
called: false,
calledOnce: false,
calledTwice: false,
calledThrice: false,
callCount: 0,
reset: function () {
this.called = false;
this.calledOnce = false;
this.calledTwice = false;
this.calledThrice = false;
this.callCount = 0;
this.args = [];
this.returnValues = [];
this.thisValues = [];
this.exceptions = [];
this.callIds = [];
},

@@ -93,10 +118,8 @@ create: function create(func) {

proxy.args = [];
proxy.returnValues = [];
proxy.thisValues = [];
proxy.exceptions = [];
proxy.callIds = [];
proxy.reset();
proxy.prototype = func.prototype;
proxy.displayName = name || "spy";
proxy.toString = sinon.functionToString;
proxy._create = sinon.spy.create;
proxy.id = "spy#" + uuid++;

@@ -107,2 +130,3 @@ return proxy;

invoke: function invoke(func, thisValue, args) {
var matching = matchingFake(this.fakes, args);
var exception, returnValue;

@@ -119,3 +143,7 @@ this.called = true;

try {
returnValue = func.apply(thisValue, args);
if (matching) {
returnValue = matching.invoke(func, thisValue, args);
} else {
returnValue = (this.func || func).apply(thisValue, args);
}
} catch (e) {

@@ -139,3 +167,3 @@ this.returnValues.push(undefined);

return spyCall.create(this.thisValues[i], this.args[i],
return spyCall.create(this, this.thisValues[i], this.args[i],
this.returnValues[i], this.exceptions[i],

@@ -163,2 +191,36 @@ this.callIds[i]);

return this.callIds[this.callCount - 1] > spyFn.callIds[spyFn.callCount - 1];
},
withArgs: function () {
var args = slice.call(arguments);
if (this.fakes) {
var match = matchingFake(this.fakes, args, true);
if (match) {
return match;
}
} else {
this.fakes = [];
}
var original = this;
var fake = this._create();
fake.matchingAguments = args;
this.fakes.push(fake);
fake.withArgs = function () {
return original.withArgs.apply(original, arguments);
};
return fake;
},
matches: function (args, strict) {
var margs = this.matchingAguments;
if (margs.length <= args.length &&
sinon.deepEqual(margs, args.slice(0, margs.length))) {
return !strict || margs.length == args.length;
}
}

@@ -183,5 +245,6 @@ };

return {
create: function create(thisValue, args, returnValue, exception, id) {
create: function create(spy, thisValue, args, returnValue, exception, id) {
var proxyCall = sinon.create(spyCall);
delete proxyCall.create;
proxyCall.proxy = spy;
proxyCall.thisValue = thisValue;

@@ -237,2 +300,27 @@ proxyCall.args = args;

return this.callId > other.callId;
},
toString: function () {
var callStr = this.proxy.toString() + "(";
var args = [];
for (var i = 0, l = this.args.length; i < l; ++i) {
args.push(sinon.format(this.args[i]));
}
callStr = callStr + args.join(", ") + ")";
if (typeof this.returnValue != "undefined") {
callStr += " => " + sinon.format(this.returnValue);
}
if (this.exception) {
callStr += " !" + this.exception.name;
if (this.exception.message) {
callStr += "(" + this.exception.message + ")";
}
}
return callStr;
}

@@ -239,0 +327,0 @@ };

@@ -15,2 +15,4 @@ /**

*/
"use strict";
(function (sinon) {

@@ -57,5 +59,76 @@ var commonJSModule = typeof module == "object" && typeof require == "function";

function getCallback(stub, args) {
if (stub.callArgAt < 0) {
for (var i = 0, l = args.length; i < l; ++i) {
if (!stub.callArgProp && typeof args[i] == "function") {
return args[i];
}
if (stub.callArgProp && args[i] &&
typeof args[i][stub.callArgProp] == "function") {
return args[i][stub.callArgProp];
}
}
return null;
}
return args[stub.callArgAt];
}
var join = Array.prototype.join;
function getCallbackError(stub, func, args) {
if (stub.callArgAt < 0) {
var msg;
if (stub.callArgProp) {
msg = sinon.functionName(stub) +
" expected to yield to '" + stub.callArgProp +
"', but no object with such a property was passed."
} else {
msg = sinon.functionName(stub) +
" expected to yield, but no callback was passed."
}
if (args.length > 0) {
msg += " Received [" + join.call(args, ", ") + "]";
}
return msg;
}
return "argument at index " + stub.callArgAt + " is not a function: " + func;
}
function callCallback(stub, args) {
if (typeof stub.callArgAt == "number") {
var func = getCallback(stub, args);
if (typeof func != "function") {
throw new TypeError(getCallbackError(stub, func, args));
}
func.apply(null, stub.callbackArguments);
}
}
var uuid = 0;
sinon.extend(stub, (function () {
var slice = Array.prototype.slice;
function throwsException(error, message) {
if (typeof error == "string") {
this.exception = new Error(message || "");
this.exception.name = error;
} else if (!error) {
this.exception = new Error("Error");
} else {
this.exception = error;
}
return this;
}
return {

@@ -68,21 +141,14 @@ create: function create() {

if (typeof functionStub.callArgAt == "number") {
var func = arguments[functionStub.callArgAt];
callCallback(functionStub, arguments);
if (typeof func != "function") {
throw new TypeError("argument at index " + functionStub.callArgAt +
" is not a function: " + func);
}
func.apply(null, functionStub.callbackArguments);
}
return functionStub.returnValue;
};
if (sinon.spy) {
functionStub = sinon.spy.create(functionStub);
}
functionStub.id = "stub#" + uuid++;
var orig = functionStub;
functionStub = sinon.spy.create(functionStub);
functionStub.func = orig;
sinon.extend(functionStub, stub);
functionStub._create = sinon.stub.create;
functionStub.displayName = "stub";

@@ -100,15 +166,5 @@ functionStub.toString = sinon.functionToString;

throws: function throws(error, message) {
if (typeof error == "string") {
this.exception = new Error(message);
this.exception.name = error;
} else if (!error) {
this.exception = new Error("Error");
} else {
this.exception = error;
}
"throws": throwsException,
throwsException: throwsException,
return this;
},
callsArg: function callsArg(pos) {

@@ -121,2 +177,4 @@ if (typeof pos != "number") {

this.callbackArguments = [];
return this;
},

@@ -131,2 +189,19 @@

this.callbackArguments = slice.call(arguments, 1);
return this;
},
yields: function () {
this.callArgAt = -1;
this.callbackArguments = slice.call(arguments, 0);
return this;
},
yieldsTo: function (prop) {
this.callArgAt = -1;
this.callArgProp = prop;
this.callbackArguments = slice.call(arguments, 1);
return this;
}

@@ -133,0 +208,0 @@ };

@@ -15,2 +15,4 @@ /**

*/
"use strict";
(function (sinon) {

@@ -33,6 +35,6 @@ var commonJSModule = typeof module == "object" && typeof require == "function";

var exception;
var exception, result;
try {
property.apply(this, arguments);
result = property.apply(this, arguments);
} catch (e) {

@@ -49,2 +51,4 @@ exception = e;

}
return result;
};

@@ -82,2 +86,4 @@ }

methods[testName] = sinon.test(method);
} else {
methods[testName] = tests[testName];
}

@@ -84,0 +90,0 @@ }

@@ -17,2 +17,4 @@ /**

*/
"use strict";
(function (sinon) {

@@ -19,0 +21,0 @@ var commonJSModule = typeof module == "object" && typeof require == "function";

@@ -21,2 +21,4 @@ /**

*/
"use strict";
(function () {

@@ -23,0 +25,0 @@ function Server() {}

@@ -17,3 +17,5 @@ /**

*/
if (typeof this.sinon == "undefined") {
"use strict";
if (typeof sinon == "undefined") {
var sinon = {};

@@ -30,7 +32,7 @@ }

function responseArray(strOrArray) {
var response = strOrArray;
function responseArray(handler) {
var response = handler;
if (Object.prototype.toString.call(strOrArray) != "[object Array]") {
response = [200, {}, strOrArray];
if (Object.prototype.toString.call(handler) != "[object Array]") {
response = [200, {}, handler];
}

@@ -49,7 +51,7 @@

function matchOne(response, requestMethod, requestUrl) {
function matchOne(response, reqMethod, reqUrl) {
var rmeth = response.method;
var matchMethod = !rmeth || rmeth.toLowerCase() == requestMethod.toLowerCase();
var matchMethod = !rmeth || rmeth.toLowerCase() == reqMethod.toLowerCase();
var url = response.url;
var matchUrl = !url || url == requestUrl || (typeof url.test == "function" && url.test(requestUrl));
var matchUrl = !url || url == reqUrl || (typeof url.test == "function" && url.test(reqUrl));

@@ -59,11 +61,17 @@ return matchMethod && matchUrl;

function match(response, requestMethod, requestUrl) {
if (matchOne(response, requestMethod, requestUrl)) {
return true;
}
function match(response, request) {
var requestMethod = this.getHTTPMethod(request);
var requestUrl = request.url;
if (!/^https?:\/\//.test(requestUrl) || rCurrLoc.test(requestUrl)) {
var strippedUrl = requestUrl.replace(rCurrLoc, "");
requestUrl = requestUrl.replace(rCurrLoc, "");
}
return matchOne(response, requestMethod, strippedUrl);
if (matchOne(response, this.getHTTPMethod(request), requestUrl)) {
if (typeof response.response == "function") {
var args = [request].concat(requestUrl.match(response.url).slice(1));
return response.response.apply(response, args);
}
return true;
}

@@ -94,2 +102,11 @@

};
if (this.autoRespond && !this.responding) {
setTimeout(function () {
server.responding = false;
server.respond();
}, this.autoRespondAfter || 10);
this.responding = true;
}
},

@@ -135,3 +152,3 @@

url: url,
response: responseArray(body)
response: typeof body == "function" ? body : responseArray(body)
});

@@ -143,8 +160,7 @@ }

var queue = this.queue || [];
var request;
for (var i = 0, l = queue.length; i < l; i++) {
this.processRequest(queue[i]);
while(request = queue.shift()) {
this.processRequest(request);
}
this.queue = [];
},

@@ -162,3 +178,3 @@

for (var i = 0, l = this.responses.length; i < l; i++) {
if (match(this.responses[i], this.getHTTPMethod(request), request.url)) {
if (match.call(this, this.responses[i], request)) {
response = this.responses[i].response;

@@ -170,3 +186,5 @@ break;

request.respond(response[0], response[1], response[2]);
if (request.readyState != 4) {
request.respond(response[0], response[1], response[2]);
}
} catch (e) {}

@@ -173,0 +191,0 @@ },

@@ -20,3 +20,5 @@ /*jslint eqeqeq: false, plusplus: false, evil: true, onevar: false, browser: true, forin: false*/

*/
if (typeof this.sinon == "undefined") {
"use strict";
if (typeof sinon == "undefined") {
var sinon = {};

@@ -254,4 +256,3 @@ }

sinon.useFakeTimers = (function () {
var global = this;
sinon.useFakeTimers = (function (global) {
var methods = ["Date", "setTimeout", "setInterval", "clearTimeout", "clearInterval"];

@@ -300,3 +301,3 @@

};
}());
}(typeof global != "undefined" ? global : this));

@@ -303,0 +304,0 @@ if (typeof module == "object" && typeof require == "function") {

@@ -11,2 +11,4 @@ /*jslint eqeqeq: false, onevar: false*/

*/
"use strict";
if (typeof sinon == "undefined") {

@@ -108,3 +110,3 @@ this.sinon = {};

if (headers.hasOwnProperty(header)) {
this.responseHeaders[header.toLowerCase()] = headers[header];
this.responseHeaders[header] = headers[header];
}

@@ -165,3 +167,11 @@ }

return this.responseHeaders[header.toLowerCase()];
header = header.toLowerCase();
for (var h in this.responseHeaders) {
if (h.toLowerCase() == header) {
return this.responseHeaders[h];
}
}
return null;
},

@@ -171,6 +181,6 @@

if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) {
return null;
return "";
}
var headers = {};
var headers = "";

@@ -180,3 +190,3 @@ for (var header in this.responseHeaders) {

!/^Set-Cookie2?$/i.test(header)) {
headers[header] = this.responseHeaders[header];
headers += header + ": " + this.responseHeaders[header] + "\r\n";
}

@@ -214,3 +224,5 @@ }

(!type || /(text\/xml)|(application\/xml)|(\+xml)/.test(type))) {
this.responseXML = FakeXMLHttpRequest.parseXML(this.responseText);
try {
this.responseXML = FakeXMLHttpRequest.parseXML(this.responseText);
} catch (e) {}
}

@@ -217,0 +229,0 @@

{
"name": "sinon",
"description": "JavaScript test spies, stubs and mocks.",
"version": "1.0.2",
"version": "1.1.0",
"homepage": "http://cjohansen.no/sinon/",

@@ -6,0 +6,0 @@ "author": "Christian Johansen",

@@ -30,1 +30,11 @@ # Sinon.JS

Check out [todo.org](http://github.com/cjohansen/Sinon.JS/raw/1.0.0/todo.org) in the project repository
## Running tests on Rhino
I've added a rudimentary setup for running the tests on Rhino with env.js (as
this is a fairly common test setup, Sinon should support it). The files are
located in test/rhino, but there are currently quite a few test failures. I
believe these are not all bugs - many are probably problems with the tests
running in Rhino. Run tests from the project root (load paths depend on it):
$ java -jar js.jar -opt -1 test/rhino/run.js

@@ -9,2 +9,4 @@ /*jslint onevar: false, eqeqeq: false*/

*/
"use strict";
function testCase(name, tests) {

@@ -11,0 +13,0 @@ var jstdCase = {};

@@ -21,2 +21,4 @@ /*jslint onevar: false, eqeqeq: false*/

*/
"use strict";
(function () {

@@ -179,2 +181,11 @@ testCase("SinonTest", {

"should not modify DOM elements when comparing them": function () {
/*:DOC += <div id="hey"></div> */
var el = document.getElementById("hey");
sinon.deepEqual(el, {})
assertSame(document.body, el.parentNode);
assertEquals(0, el.childNodes.length);
},
"should pass deep objects": function () {

@@ -181,0 +192,0 @@ var func = function () {};

@@ -26,2 +26,4 @@ /*jslint onevar: false*/

*/
"use strict";
(function (global) {

@@ -587,5 +589,6 @@ testCase("SinonAssertTest", {

"should fail when method fails": function () {
this.stub.callCount = 2;
this.stub();
this.stub();
var stub = this.stub;
assertException(function () {

@@ -635,6 +638,7 @@ sinon.assert.callCount(stub, 3);

"should fail if stub returns false": function () {
sinon.stub(this.stub, "alwaysCalledOn").returns(false);
var stub = sinon.stub();
sinon.stub(stub, "alwaysCalledOn").returns(false);
assertException(function () {
sinon.assert.alwaysCalledOn(this.stub, {});
sinon.assert.alwaysCalledOn(stub, {});
});

@@ -841,3 +845,3 @@

assertEquals("expected doSomething to not have been called " +
"but was called once",
"but was called once\n doSomething()",
this.message("notCalled", this.obj.doSomething));

@@ -853,6 +857,19 @@ },

assertEquals("expected doSomething to not have been called " +
"but was called 4 times",
"but was called 4 times\n doSomething()\n " +
"doSomething()\n doSomething()\n doSomething()",
this.message("notCalled", this.obj.doSomething));
},
"assert.notCalled exception message with calls with arguments": function () {
this.obj.doSomething();
this.obj.doSomething(3);
this.obj.doSomething(42, 1);
this.obj.doSomething();
assertEquals("expected doSomething to not have been called " +
"but was called 4 times\n doSomething()\n " +
"doSomething(3)\n doSomething(42, 1)\n doSomething()",
this.message("notCalled", this.obj.doSomething));
},
"assert.callOrder exception message": function () {

@@ -875,3 +892,4 @@ var obj = { doop: function () {}, foo: function () {} };

assertEquals("expected doSomething to be called thrice but was called once",
assertEquals("expected doSomething to be called thrice but was called " +
"once\n doSomething()",
this.message("callCount", this.obj.doSomething, 3));

@@ -884,3 +902,4 @@ },

assertEquals("expected doSomething to be called once but was called twice",
assertEquals("expected doSomething to be called once but was called " +
"twice\n doSomething()\n doSomething()",
this.message("calledOnce", this.obj.doSomething));

@@ -890,3 +909,4 @@

assertEquals("expected doSomething to be called once but was called thrice",
assertEquals("expected doSomething to be called once but was called " +
"thrice\n doSomething()\n doSomething()\n doSomething()",
this.message("calledOnce", this.obj.doSomething));

@@ -898,3 +918,4 @@ },

assertEquals("expected doSomething to be called twice but was called once",
assertEquals("expected doSomething to be called twice but was called " +
"once\n doSomething()",
this.message("calledTwice", this.obj.doSomething));

@@ -909,3 +930,3 @@ },

assertEquals("expected doSomething to be called thrice but was called 4 times",
assertEquals("expected doSomething to be called thrice but was called 4 times\n doSomething()\n doSomething()\n doSomething()\n doSomething()",
this.message("calledThrice", this.obj.doSomething));

@@ -919,12 +940,25 @@ },

var obj = {
toString: function () {
return "[Oh no]";
}
var obj = { toString: function () { return "[Oh no]"; } };
var obj2 = { toString: function () { return "[Oh well]"; } };
this.obj.doSomething.call(obj);
this.obj.doSomething.call(obj2);
assertEquals("expected doSomething to be called with [Oh yeah] as this but was called with [Oh no], [Oh well]",
this.message("calledOn", this.obj.doSomething, this.obj));
},
"assert.alwaysCalledOn exception message": function () {
this.obj.toString = function () {
return "[Oh yeah]";
};
var obj = { toString: function () { return "[Oh no]"; } };
var obj2 = { toString: function () { return "[Oh well]"; } };
this.obj.doSomething.call(obj);
this.obj.doSomething.call(obj2);
this.obj.doSomething();
assertEquals("expected doSomething to always be called with [Oh yeah] as this",
assertEquals("expected doSomething to always be called with [Oh yeah] as this but was called with [Oh no], [Oh well], [Oh yeah]",
this.message("alwaysCalledOn", this.obj.doSomething, this.obj));

@@ -936,3 +970,4 @@ },

assertEquals("expected doSomething to be called with arguments 4, 3, hey",
assertEquals("expected doSomething to be called with arguments 4, 3, " +
"hey\n doSomething(1, 3, hey)",
this.message("calledWith", this.obj.doSomething, 4, 3, "hey"));

@@ -945,3 +980,4 @@ },

assertEquals("expected doSomething to always be called with arguments 1, hey",
assertEquals("expected doSomething to always be called with arguments 1" +
", hey\n doSomething(1, 3, hey)\n doSomething(1, hey)",
this.message("alwaysCalledWith", this.obj.doSomething, 1, "hey"));

@@ -953,3 +989,4 @@ },

assertEquals("expected doSomething to be called with exact arguments 1, 3",
assertEquals("expected doSomething to be called with exact arguments 1" +
", 3\n doSomething(1, 3, hey)",
this.message("calledWithExactly", this.obj.doSomething, 1, 3));

@@ -963,7 +1000,26 @@ },

assertEquals("expected doSomething to always be called with exact " +
"arguments 1, 3",
"arguments 1, 3\n doSomething(1, 3, hey)\n " +
"doSomething(1, 3)",
this.message("alwaysCalledWithExactly",
this.obj.doSomething, 1, 3));
},
"assert.threw exception message": function () {
this.obj.doSomething(1, 3, "hey");
this.obj.doSomething(1, 3);
assertEquals("doSomething did not throw exception\n" +
" doSomething(1, 3, hey)\n doSomething(1, 3)",
this.message("threw", this.obj.doSomething));
},
"assert.alwaysThrew exception message": function () {
this.obj.doSomething(1, 3, "hey");
this.obj.doSomething(1, 3);
assertEquals("doSomething did not always throw exception\n" +
" doSomething(1, 3, hey)\n doSomething(1, 3)",
this.message("alwaysThrew", this.obj.doSomething));
}
});
}(this));

@@ -20,2 +20,4 @@ /*jslint onevar: false, eqeqeq: false, plusplus: false*/

*/
"use strict";
(function () {

@@ -45,3 +47,3 @@ testCase("CollectionCreateTest", {

"should call stub": function () {
var object = { id: 42 };
var object = { method: function () {} };
var args;

@@ -59,3 +61,3 @@

"should add stub to fake array": function () {
var object = { id: 42 };
var object = { method: function () {} };

@@ -79,4 +81,4 @@ sinon.stub = function () {

this.collection.stub({}, "method");
this.collection.stub({}, "method");
this.collection.stub({ method: function () {} }, "method");
this.collection.stub({ method: function () {} }, "method");

@@ -87,2 +89,31 @@ assertEquals(objects, this.collection.fakes);

testCase("CollectionStubAnythingTest", {
setUp: function () {
this.object = { property: 42 };
this.collection = sinon.create(sinon.collection);
},
"should stub number property": function () {
this.collection.stub(this.object, "property", 1);
assertEquals(1, this.object.property);
},
"should restore number property": function () {
this.collection.stub(this.object, "property", 1);
this.collection.restore();
assertEquals(42, this.object.property);
},
"should fail if property does not exist": function () {
var collection = this.collection;
var object = {};
assertException(function () {
collection.stub(object, "prop", 1);
});
}
});
testCase("CollectionMockTest", {

@@ -158,4 +189,4 @@ setUp: function () {

this.collection.mock({}, "method");
this.collection.stub({}, "method");
this.collection.mock({ method: function () {} }, "method");
this.collection.stub({ method: function () {} }, "method");

@@ -162,0 +193,0 @@ assertEquals(objects, this.collection.fakes);

@@ -20,2 +20,4 @@ /*jslint onevar: false*/

*/
"use strict";
(function () {

@@ -605,3 +607,3 @@ testCase("MockCreateTest", {

} catch (e) {
assertEquals("myMeth expected to be called once, but was called 0 times", e.message);
assertEquals("Expected myMeth([...]) once (never called)", e.message);
}

@@ -631,2 +633,161 @@ }

assertSame(this.method, this.object.method);
},
"should include all calls in error message": function () {
var mock = this.mock;
mock.expects("method").thrice();
mock.expects("method").once().withArgs(42);
var message;
try {
mock.verify();
} catch (e) {
message = e.message;
}
assertEquals("Expected method([...]) thrice (never called)\nExpected method(42[, ...]) once (never called)", message);
},
"should include exact expected arguments in error message": function () {
var mock = this.mock;
mock.expects("method").once().withExactArgs(42);
var message;
try {
mock.verify();
} catch (e) {
message = e.message;
}
assertEquals("Expected method(42) once (never called)", message);
},
"should include received call count in error message": function () {
var mock = this.mock;
mock.expects("method").thrice().withExactArgs(42);
this.object.method(42);
var message;
try {
mock.verify();
} catch (e) {
message = e.message;
}
assertEquals("Expected method(42) thrice (called once)", message);
},
"should include unexpected calls in error message": function () {
var mock = this.mock;
mock.expects("method").thrice().withExactArgs(42);
var message;
try {
this.object.method();
} catch (e) {
message = e.message;
}
assertEquals("Unexpected call: method()\n" +
" Expected method(42) thrice (never called)", message);
},
"should include met expectations in error message": function () {
var mock = this.mock;
mock.expects("method").once().withArgs(1);
mock.expects("method").thrice().withExactArgs(42);
this.object.method(1);
var message;
try {
this.object.method();
} catch (e) {
message = e.message;
}
assertEquals("Unexpected call: method()\n" +
" Expectation met: method(1[, ...]) once\n" +
" Expected method(42) thrice (never called)", message);
},
"should include met expectations in error message from verify": function () {
var mock = this.mock;
mock.expects("method").once().withArgs(1);
mock.expects("method").thrice().withExactArgs(42);
this.object.method(1);
var message;
try {
mock.verify();
} catch (e) {
message = e.message;
}
assertEquals("Expected method(42) thrice (never called)\n" +
"Expectation met: method(1[, ...]) once", message);
},
"should report min calls in error message": function () {
var mock = this.mock;
mock.expects("method").atLeast(1);
var message;
try {
mock.verify();
} catch (e) {
message = e.message;
}
assertEquals("Expected method([...]) at least once (never called)", message);
},
"should report max calls in error message": function () {
var mock = this.mock;
mock.expects("method").atMost(2);
var message;
try {
this.object.method();
this.object.method();
this.object.method();
} catch (e) {
message = e.message;
}
assertEquals("Unexpected call: method()\n" +
" Expectation met: method([...]) at most twice", message);
},
"should report min calls in met expectation": function () {
var mock = this.mock;
mock.expects("method").atLeast(1);
mock.expects("method").withArgs(2).once();
var message;
try {
this.object.method();
this.object.method(2);
this.object.method(2);
} catch (e) {
message = e.message;
}
assertEquals("Unexpected call: method(2)\n" +
" Expectation met: method([...]) at least once\n" +
" Expectation met: method(2[, ...]) once", message);
},
"should report max and min calls in error messages": function () {
var mock = this.mock;
mock.expects("method").atLeast(1).atMost(2);
var message;
try {
mock.verify();
} catch (e) {
message = e.message;
}
assertEquals("Expected method([...]) at least once and at most twice " +
"(never called)", message);
}

@@ -721,2 +882,29 @@ });

}, "ExpectationError");
},
"should allow mock calls in any order": function () {
var object = { method: function () {} };
var mock = sinon.mock(object);
mock.expects("method").once().withArgs(42);
mock.expects("method").twice().withArgs("Yeah");
assertNoException(function () {
object.method("Yeah");
});
assertNoException(function () {
object.method(42);
});
assertException(function () {
object.method(1);
});
assertNoException(function () {
object.method("Yeah");
});
assertException(function () {
object.method(42);
});
}

@@ -742,2 +930,26 @@ });

});
testCase("MockExpectationYieldsTest", {
"should invoke only argument as callback": function () {
var mock = sinon.mock().yields();
var spy = sinon.spy();
mock(spy);
assert(spy.calledOnce);
assertEquals(0, spy.args[0].length);
},
"should throw understandable error if no callback is passed": function () {
var mock = sinon.mock().yields();
var spy = sinon.spy();
try {
mock();
throw new Error();
} catch (e) {
assertEquals("stub expected to yield, but no callback was passed.",
e.message);
}
}
});
}());

@@ -24,3 +24,5 @@ /*jslint onevar: false*/

*/
(function () {
"use strict";
(function (global) {
testCase("SandboxTest", {

@@ -89,5 +91,4 @@ "should be object": function () {

var global = this;
var globalXHR = this.XMLHttpRequest;
var globalAXO = this.ActiveXObject;
var globalXHR = global.XMLHttpRequest;
var globalAXO = global.ActiveXObject;

@@ -420,2 +421,2 @@ testCase("SandboxUseFakeXMLHttpRequestTest", {

});
}());
}(this));

@@ -23,2 +23,4 @@ /*jslint onevar: false, eqeqeq: false*/

*/
"use strict";
(function () {

@@ -1084,3 +1086,3 @@ testCase("SpyCreateTest", {

this.returnValue = function () {};
this.call = sinon.spyCall.create(this.thisValue, this.args, this.returnValue);
this.call = sinon.spyCall.create(function () {}, this.thisValue, this.args, this.returnValue);
}

@@ -1199,3 +1201,3 @@

"should return true for no arguments": function () {
var call = sinon.spyCall.create({}, []);
var call = sinon.spyCall.create(function () {}, {}, []);

@@ -1206,3 +1208,3 @@ assert(call.calledWithExactly());

"should return false when called with no args but matching one": function () {
var call = sinon.spyCall.create({}, []);
var call = sinon.spyCall.create(function () {}, {}, []);

@@ -1213,2 +1215,88 @@ assertFalse(call.calledWithExactly({}));

testCase("SpyCallToStringTest", {
setUp: function () {
this.format = sinon.format;
},
tearDown: function () {
sinon.format = this.format;
},
"should include spy name": function () {
var object = { doIt: sinon.spy() };
object.doIt();
assertEquals("doIt()", object.doIt.getCall(0).toString());
},
"should include single argument": function () {
var object = { doIt: sinon.spy() };
object.doIt(42);
assertEquals("doIt(42)", object.doIt.getCall(0).toString());
},
"should include all arguments": function () {
var object = { doIt: sinon.spy() };
object.doIt(42, "Hey");
assertEquals("doIt(42, Hey)", object.doIt.getCall(0).toString());
},
"should include explicit return value": function () {
var object = { doIt: sinon.stub().returns(42) };
object.doIt(42, "Hey");
assertEquals("doIt(42, Hey) => 42", object.doIt.getCall(0).toString());
},
"should include empty string return value": function () {
var object = { doIt: sinon.stub().returns("") };
object.doIt(42, "Hey");
assertEquals("doIt(42, Hey) => ", object.doIt.getCall(0).toString());
},
"should include exception": function () {
var object = { doIt: sinon.stub().throws("TypeError") };
try {
object.doIt();
} catch (e) {}
assertEquals("doIt() !TypeError", object.doIt.getCall(0).toString());
},
"should include exception message if any": function () {
var object = { doIt: sinon.stub().throws("TypeError", "Oh noes!") };
try {
object.doIt();
} catch (e) {}
assertEquals("doIt() !TypeError(Oh noes!)",
object.doIt.getCall(0).toString());
},
"should format arguments with sinon.format": function () {
sinon.format = sinon.stub().returns("Forty-two");
var object = { doIt: sinon.spy() };
object.doIt(42);
assertEquals("doIt(Forty-two)", object.doIt.getCall(0).toString());
assert(sinon.format.calledWith(42));
},
"should format return value with sinon.format": function () {
sinon.format = sinon.stub().returns("Forty-two");
var object = { doIt: sinon.stub().returns(42) };
object.doIt();
assertEquals("doIt() => Forty-two", object.doIt.getCall(0).toString());
assert(sinon.format.calledWith(42));
}
});
testCase("SpyConstructorTest", {

@@ -1287,2 +1375,119 @@ setUp: function () {

});
testCase("SpyResetTest", {
"should reset spy state": function () {
var spy = sinon.spy();
spy();
spy.reset();
assert(!spy.called);
assert(!spy.calledOnce);
assertEquals(0, spy.args.length);
assertEquals(0, spy.returnValues.length);
assertEquals(0, spy.exceptions.length);
assertEquals(0, spy.thisValues.length);
},
"should reset call order state": function () {
var spies = [sinon.spy(), sinon.spy()];
spies[0]();
spies[1]();
spies[0].reset();
assert(!spies[0].calledBefore(spies[1]));
}
});
testCase("WithArgsTest", {
"should define withArgs method": function () {
var spy = sinon.spy();
assertFunction(spy.withArgs);
},
"should record single call": function () {
var spy = sinon.spy().withArgs(1);
spy(1);
assertEquals(1, spy.callCount);
},
"should record non-matching call on original spy": function () {
var spy = sinon.spy();
var argSpy = spy.withArgs(1);
spy(1);
spy(2);
assertEquals(2, spy.callCount);
assertEquals(1, argSpy.callCount);
},
"should record non-matching call with several arguments separately": function () {
var spy = sinon.spy();
var argSpy = spy.withArgs(1, "str", {});
spy(1);
spy(1, "str", {});
assertEquals(2, spy.callCount);
assertEquals(1, argSpy.callCount);
},
"should record for partial argument match": function () {
var spy = sinon.spy();
var argSpy = spy.withArgs(1, "str", {});
spy(1);
spy(1, "str", {});
spy(1, "str", {}, []);
assertEquals(3, spy.callCount);
assertEquals(2, argSpy.callCount);
},
"should record filtered spy when original throws": function () {
var spy = sinon.spy(function () {
throw new Error("Oops");
});
var argSpy = spy.withArgs({}, []);
assertException(function () {
spy(1);
});
assertException(function () {
spy({}, []);
});
assertEquals(2, spy.callCount);
assertEquals(1, argSpy.callCount);
},
"should return existing override for arguments": function () {
var spy = sinon.spy();
var argSpy = spy.withArgs({}, []);
var another = spy.withArgs({}, []);
spy();
spy({}, []);
spy({}, [], 2);
assertSame(argSpy, another);
assertNotSame(spy, another);
assertEquals(3, spy.callCount);
assertEquals(2, spy.withArgs({}, []).callCount);
},
"should chain withArgs calls on original spy": function () {
var spy = sinon.spy();
var numArgSpy = spy.withArgs({}, []).withArgs(3);
spy();
spy({}, []);
spy(3);
assertEquals(3, spy.callCount);
assertEquals(1, numArgSpy.callCount);
assertEquals(1, spy.withArgs({}, []).callCount);
}
});
}());

@@ -20,2 +20,4 @@ /*jslint onevar: false*/

*/
"use strict";
(function () {

@@ -108,2 +110,14 @@ testCase("StubCreateTest", {

"should not specify exception message if not provided": function () {
var stub = sinon.stub.create();
stub.throws("Error");
try {
stub();
fail("Expected stub to throw");
} catch (e) {
assertEquals("", e.message);
}
},
"should throw generic error": function () {

@@ -133,2 +147,8 @@ var stub = sinon.stub.create();

"should return stub": function () {
var stub = this.stub.callsArg(2);
assertFunction(stub);
},
"should throw if argument at specified index is not callable": function () {

@@ -174,2 +194,8 @@ this.stub.callsArg(0);

"should return function": function () {
var stub = this.stub.callsArgWith(2, 3);
assertFunction(stub);
},
"should call callback without args": function () {

@@ -412,2 +438,194 @@ this.stub.callsArgWith(1);

});
testCase("StubYieldsTest", {
"should invoke only argument as callback": function () {
var stub = sinon.stub().yields();
var spy = sinon.spy();
stub(spy);
assert(spy.calledOnce);
assertEquals(0, spy.args[0].length);
},
"should throw understandable error if no callback is passed": function () {
var stub = sinon.stub().yields();
var spy = sinon.spy();
try {
stub();
throw new Error();
} catch (e) {
assertEquals("stub expected to yield, but no callback was passed.",
e.message);
}
},
"should include stub name and actual arguments in error": function () {
var myObj = { somethingAwesome: function () {} };
var stub = sinon.stub(myObj, "somethingAwesome").yields();
var spy = sinon.spy();
try {
stub(23, 42);
throw new Error();
} catch (e) {
assertEquals("somethingAwesome expected to yield, but no callback " +
"was passed. Received [23, 42]", e.message);
}
},
"should invoke last argument as callback": function () {
var stub = sinon.stub().yields();
var spy = sinon.spy();
stub(24, {}, spy);
assert(spy.calledOnce);
assertEquals(0, spy.args[0].length);
},
"should invoke first of two callbacks": function () {
var stub = sinon.stub().yields();
var spy = sinon.spy();
var spy2 = sinon.spy();
stub(24, {}, spy, spy2);
assert(spy.calledOnce);
assert(!spy2.called);
},
"should invoke callback with arguments": function () {
var obj = { id: 42 };
var stub = sinon.stub().yields(obj, "Crazy");
var spy = sinon.spy();
stub(spy);
assert(spy.calledWith(obj, "Crazy"));
},
"should throw if callback throws": function () {
var obj = { id: 42 };
var stub = sinon.stub().yields(obj, "Crazy");
var callback = sinon.stub().throws();
assertException(function () {
stub(spy);
});
}
});
// yieldsTo burde kunne kalles flere ganger?
testCase("StubYieldsToTest", {
"should yield to property of object argument": function () {
var stub = sinon.stub().yieldsTo("success");
var callback = sinon.spy();
stub({ success: callback });
assert(callback.calledOnce);
assertEquals(0, callback.args[0].length);
},
"should throw understandable error if no object with callback is passed": function () {
var stub = sinon.stub().yieldsTo("success");
try {
stub();
throw new Error();
} catch (e) {
assertEquals("stub expected to yield to 'success', but no object "+
"with such a property was passed.",
e.message);
}
},
"should include stub name and actual arguments in error": function () {
var myObj = { somethingAwesome: function () {} };
var stub = sinon.stub(myObj, "somethingAwesome").yieldsTo("success");
try {
stub(23, 42);
throw new Error();
} catch (e) {
assertEquals("somethingAwesome expected to yield to 'success', but " +
"no object with such a property was passed. " +
"Received [23, 42]", e.message);
}
},
"should invoke property on last argument as callback": function () {
var stub = sinon.stub().yieldsTo("success");
var callback = sinon.spy();
stub(24, {}, { success: callback });
assert(callback.calledOnce);
assertEquals(0, callback.args[0].length);
},
"should invoke first of two possible callbacks": function () {
var stub = sinon.stub().yieldsTo("error");
var callback = sinon.spy();
var callback2 = sinon.spy();
stub(24, {}, { error: callback }, { error: callback2 });
assert(callback.calledOnce);
assert(!callback2.called);
},
"should invoke callback with arguments": function () {
var obj = { id: 42 };
var stub = sinon.stub().yieldsTo("success", obj, "Crazy");
var callback = sinon.spy();
stub({ success: callback });
assert(callback.calledWith(obj, "Crazy"));
},
"should throw if callback throws": function () {
var obj = { id: 42 };
var stub = sinon.stub().yieldsTo("error", obj, "Crazy");
var callback = sinon.stub().throws();
assertException(function () {
stub({ error: callback });
});
}
});
testCase("StubWithArgsTest", {
"should define withArgs method": function () {
var stub = sinon.stub();
assertFunction(stub.withArgs);
},
"should create filtered stub": function () {
var stub = sinon.stub();
var other = stub.withArgs(23);
assertNotSame(stub, other);
assertFunction(stub.returns);
assertFunction(other.returns);
},
"should filter return values based on arguments": function () {
var stub = sinon.stub().returns(23);
stub.withArgs(42).returns(99);
assertEquals(23, stub());
assertEquals(99, stub(42));
},
"should filter exceptions based on arguments": function () {
var stub = sinon.stub().returns(23);
stub.withArgs(42).throws();
assertNoException(function () {
stub();
});
assertException(function () {
stub(42);
});
}
});
}());

@@ -18,2 +18,4 @@ /*jslint onevar: false*/

*/
"use strict";
(function () {

@@ -176,4 +178,50 @@ testCase("SinonTestCaseTest", {

assertSame(myMeth, myObj.meth);
},
"should allow the use of helper methods": function () {
var helper = sinon.spy();
var testC = sinon.testCase({
doIt: helper,
testIt: function () {
this.doIt();
}
});
assertNoException(function () {
testC.testIt();
});
assert(helper.calledOnce);
assert(helper.calledOn(testC));
},
"should return result of test function": function () {
var testC = sinon.testCase({
testIt: sinon.stub().returns(42)
});
assertEquals(42, testC.testIt());
},
"should return result of test function with setUp": function () {
var testC = sinon.testCase({
setUp: sinon.spy(),
testIt: sinon.stub().returns(42)
});
assertEquals(42, testC.testIt());
},
"should return result of test function with setUp and teardown": function () {
var testC = sinon.testCase({
setUp: sinon.spy(),
tearDown: sinon.spy(),
testIt: sinon.stub().returns(42)
});
assertEquals(42, testC.testIt());
}
});
}());

@@ -22,2 +22,4 @@ /*jslint onevar: false, eqeqeq: false, browser: true*/

*/
"use strict";
(function () {

@@ -53,3 +55,3 @@ testCase("SinonTestTest", {

assertSame(object, object.method());
})();
}).call({});
},

@@ -63,3 +65,3 @@

this.stub(object, "method");
})();
}).call({});

@@ -77,3 +79,3 @@ assertSame(method, object.method);

throw new Error();
})();
}).call({});
}, "Error");

@@ -90,3 +92,3 @@ },

throw new Error();
})();
}).call({});
} catch (e) {}

@@ -105,3 +107,3 @@

assertSame(object, object.method());
})();
}).call({});
},

@@ -116,3 +118,3 @@

this.mock(object).expects("method");
})();
}).call({});
}, "ExpectationError");

@@ -130,3 +132,3 @@

this.mock(object).expects("method");
})();
}).call({});
} catch (e) {}

@@ -145,3 +147,3 @@

object.method();
})();
}).call({});
} catch (e) {}

@@ -148,0 +150,0 @@

@@ -22,2 +22,4 @@ /*jslint onevar: false, browser: false, regexp: false, browser: true*/

*/
"use strict";
testCase("ServerCreateTest", {

@@ -205,3 +207,3 @@ tearDown: function () {

assertEquals(210, this.getRootSync.status);
assertEquals({ "x-ops": "Yeah" }, this.getRootSync.getAllResponseHeaders());
assertEquals("X-Ops: Yeah\r\n", this.getRootSync.getAllResponseHeaders());
assertEquals("Body, man", this.getRootSync.responseText);

@@ -214,3 +216,3 @@ },

assertEquals(404, this.getRootSync.status);
assertEquals({}, this.getRootSync.getAllResponseHeaders());
assertEquals("", this.getRootSync.getAllResponseHeaders());
assertEquals("", this.getRootSync.responseText);

@@ -405,2 +407,118 @@ },

testCase("ServerRespondWithFunctionHandlerTest", {
setUp: function () {
this.server = sinon.fakeServer.create();
},
tearDown: function () {
this.server.restore();
},
"should yield response to request function handler": function () {
var handler = sinon.spy();
this.server.respondWith("/hello", handler);
var xhr = new sinon.FakeXMLHttpRequest();
xhr.open("GET", "/hello");
xhr.send();
this.server.respond();
assert(handler.calledOnce);
assert(handler.calledWith(xhr));
},
"should respond to request from function handler": function () {
this.server.respondWith("/hello", function (xhr) {
xhr.respond(200, { "Content-Type": "application/json" }, '{"id":42}');
});
var request = new sinon.FakeXMLHttpRequest();
request.open("GET", "/hello");
request.send();
this.server.respond();
assertEquals(200, request.status);
assertEquals({ "Content-Type": "application/json" }, request.responseHeaders);
assertEquals('{"id":42}', request.responseText);
},
"should yield response to request function handler when method matches": function () {
var handler = sinon.spy();
this.server.respondWith("GET", "/hello", handler);
var xhr = new sinon.FakeXMLHttpRequest();
xhr.open("GET", "/hello");
xhr.send();
this.server.respond();
assert(handler.calledOnce);
},
"should not yield response to request function handler when method does not match": function () {
var handler = sinon.spy();
this.server.respondWith("GET", "/hello", handler);
var xhr = new sinon.FakeXMLHttpRequest();
xhr.open("POST", "/hello");
xhr.send();
this.server.respond();
assert(!handler.called);
},
"should yield response to request function handler when regexp url matches": function () {
var handler = sinon.spy();
this.server.respondWith("GET", /\/.*/, handler);
var xhr = new sinon.FakeXMLHttpRequest();
xhr.open("GET", "/hello");
xhr.send();
this.server.respond();
assert(handler.calledOnce);
},
"should not yield response to request function handler when regexp url does not match": function () {
var handler = sinon.spy();
this.server.respondWith("GET", /\/a.*/, handler);
var xhr = new sinon.FakeXMLHttpRequest();
xhr.open("GET", "/hello");
xhr.send();
this.server.respond();
assert(!handler.called);
},
"should not process request further if processed by function": function () {
var handler = sinon.spy();
this.server.respondWith("GET", /\/a.*/, handler);
this.server.respondWith("GET", "/aloha", [200, {}, "Oh hi"]);
var xhr = new sinon.FakeXMLHttpRequest();
xhr.respond = sinon.spy();
xhr.open("GET", "/aloha");
xhr.send();
this.server.respond();
assert(handler.called);
assert(xhr.respond.calledOnce);
},
"should yield URL capture groups to response handler": function () {
var handler = sinon.spy();
this.server.respondWith("GET", /\/people\/(\d+)/, handler);
var xhr = new sinon.FakeXMLHttpRequest();
xhr.respond = sinon.spy();
xhr.open("GET", "/people/3");
xhr.send();
this.server.respond();
assert(handler.called);
assertEquals([xhr, 3], handler.args[0]);
}
});
testCase("ServerRespondFakeHTTPVerbTest", {

@@ -471,1 +589,75 @@ setUp: function () {

});
(function () {
function get(url) {
var request = new sinon.FakeXMLHttpRequest();
sinon.spy(request, "respond");
request.open("get", "/path", true);
request.send();
return request;
}
testCase("ServerAutoResponseTest", {
setUp: function () {
this.server = sinon.fakeServer.create();
this.clock = sinon.useFakeTimers();
},
tearDown: function () {
this.server.restore();
this.clock.restore();
},
"should respond async automatically after 10ms": function () {
this.server.autoRespond = true;
var request = get("/path");
this.clock.tick(10);
assertTrue(request.respond.calledOnce);
},
"normal server should not respond automatically": function () {
var request = get("/path");
this.clock.tick(100);
assertTrue(!request.respond.called);
},
"should only auto-respond once": function () {
this.server.autoRespond = true;
var requests = [get("/path")];
this.clock.tick(5);
requests.push(get("/other"));
this.clock.tick(5);
assertTrue(requests[0].respond.calledOnce);
assertTrue(requests[1].respond.calledOnce);
},
"should auto-respond after having already responded": function () {
this.server.autoRespond = true;
var requests = [get("/path")];
this.clock.tick(10);
requests.push(get("/other"));
this.clock.tick(10);
assertTrue(requests[0].respond.calledOnce);
assertTrue(requests[1].respond.calledOnce);
},
"should set auto-respond timeout to 50ms": function () {
this.server.autoRespond = true;
this.server.autoRespondAfter = 50;
var request = get("/path");
this.clock.tick(49);
assertFalse(request.respond.called);
this.clock.tick(1);
assertTrue(request.respond.calledOnce);
}
});
}());

@@ -22,2 +22,4 @@ /*jslint onevar: false, browser: false, regexp: false, browser: true*/

*/
"use strict";
testCase("ServerWithClockTest", {

@@ -24,0 +26,0 @@ setUp: function () {

@@ -27,2 +27,4 @@ /*jslint onevar: false, eqeqeq: false, plusplus: false*/

*/
"use strict";
(function (global) {

@@ -187,3 +189,3 @@ testCase("SetTimeOutTest", {

"should call function with global object as this": function () {
"should call function with global object or null (strict mode) as this": function () {
var stub = sinon.stub.create().throws();

@@ -193,3 +195,3 @@ this.clock.setTimeout(stub, 100);

assert(stub.calledOn(global));
assert(stub.calledOn(global) || stub.calledOn(null));
},

@@ -196,0 +198,0 @@

@@ -27,2 +27,4 @@ /*jslint onevar: false, eqeqeq: false, browser: true*/

*/
"use strict";
(function (global) {

@@ -601,3 +603,3 @@ testCase("FakeXMLHttpRequestTest", {

assertEquals(200, this.xhr.status);
assertEquals({}, this.xhr.getAllResponseHeaders());
assertEquals("", this.xhr.getAllResponseHeaders());
assertEquals("", this.xhr.responseText);

@@ -682,4 +684,4 @@ },

"should return null if request is not finished": function () {
assertNull(this.xhr.getAllResponseHeaders());
"should return empty string if request is not finished": function () {
assertEquals("", this.xhr.getAllResponseHeaders());
},

@@ -694,3 +696,3 @@

assertEquals({}, this.xhr.getAllResponseHeaders());
assertEquals("", this.xhr.getAllResponseHeaders());
},

@@ -706,6 +708,3 @@

assertEquals({
"content-type": "text/html",
"content-length": "32"
}, this.xhr.getAllResponseHeaders());
assertEquals("Content-Type: text/html\r\nContent-Length: 32\r\n", this.xhr.getAllResponseHeaders());
}

@@ -883,4 +882,4 @@ });

var globalXMLHttpRequest = this.XMLHttpRequest;
var globalActiveXObject = this.ActiveXObject;
var globalXMLHttpRequest = global.XMLHttpRequest;
var globalActiveXObject = global.ActiveXObject;

@@ -887,0 +886,0 @@ var fakeXhrSetUp = function () {

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc