Socket
Socket
Sign inDemoInstall

sinon

Package Overview
Dependencies
Maintainers
2
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.3.4 to 1.4.0

.travis.yml

33

Changelog.txt

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

== 1.4.0 / 2012-07-09
* Argument matchers (Maximillian Antoni)
sinon.match.{any, same, typeOf, instanceOf, has, hasOwn, defined, truthy,
falsy} as well as typeOf shortcuts for boolean, number, string, object,
function, array, regexp and date. The result of a call can be used with
spy.calledWith.
* spy.returned now works with matchers and compares objects deeply.
* Matcher assertions: calledWithMatch, alwaysCalledWithMatch and
neverCalledWithMatch
* calledWithNew and alwaysCalledWithNew for assert (Maximilian Antoni)
* Easier stubbed fluent interfaces: stub.returnsThis() (Glen Mailer)
* allow yields() and family to be used along with returns()/throws() and
family (Glen Mailer)
* Async versions `callsArg*` and `yields*` for stubs (TEHEK)
* Format args when doing `spy.printf("%*")` (Domenic Denicola)
* Add notCalled property to spies
* Fix: spy.reset did not reset fakes created by spy.withArgs (Maximilian Antoni)
* Properly restore stubs when stubbing entire objects through the sandbox
(Konrad Holowinski)
* Restore global methods properly - delete properties that where not own
properties (Keith Cirkel)
* setTimeout and setInterval pass arguments (Rodion Vynnychenko)
* Timer callbacks that contain a clock.tick no longer fails (Wesley Waser)
* spy(undefined, "property") now throws
* Prevent multiple restore for fake timers (Kevin Decker)
* Fix toString format under Node (Kevin Decker)
* Mock expectations emit success and failure events (Kevin Decker)
* Development improvement: Use Buster.JS to test Sinon
* Fix bug where expect.atLeast failed when minimum calls where received
* Make fake server safe to load on node.js
* Add support for no args on .withArgs and .withExactArgs (Tek Nynja)
* Avoid hasOwnProperty for host objects
== 1.3.2 / 2012-03-11

@@ -2,0 +35,0 @@ * Stronger Node inference in sandbox

24

lib/sinon.js

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

method.restore = function () {
if(owned) {
object[property] = wrappedMethod;
} else {
// For prototype properties try to reset by delete first.
// If this fails (ex: localStorage on mobile safari) then force a reset
// via direct assignment.
if (!owned) {
delete object[property];
}
if (object[property] === method) {
object[property] = wrappedMethod;
}
};

@@ -123,2 +127,5 @@

deepEqual: function deepEqual(a, b) {
if (sinon.match && sinon.match.isMatcher(a)) {
return a.test(b);
}
if (typeof a != "object" || typeof b != "object") {

@@ -275,2 +282,10 @@ return a === b;

}, 0);
},
typeOf: function (value) {
if (value === null) {
return "null";
}
var string = Object.prototype.toString.call(value);
return string.substring(8, string.length - 1).toLowerCase();
}

@@ -295,2 +310,3 @@ };

module.exports.assert = require("./sinon/assert");
module.exports.match = require("./sinon/match");
}

@@ -308,3 +324,3 @@

sinon.format = function (value) {
return typeof value == "object" ? util.inspect(value) : value;
return typeof value == "object" && value.toString === Object.prototype.toString ? util.inspect(value) : value;
};

@@ -311,0 +327,0 @@ } catch (e) {

@@ -158,7 +158,12 @@ /**

mirrorPropAsAssertion("alwaysCalledOn", "expected %n to always be called with %1 as this but was called with %t");
mirrorPropAsAssertion("calledWithNew", "expected %n to be called with new");
mirrorPropAsAssertion("alwaysCalledWithNew", "expected %n to always be called with new");
mirrorPropAsAssertion("calledWith", "expected %n to be called with arguments %*%C");
mirrorPropAsAssertion("calledWithMatch", "expected %n to be called with match %*%C");
mirrorPropAsAssertion("alwaysCalledWith", "expected %n to always be called with arguments %*%C");
mirrorPropAsAssertion("alwaysCalledWithMatch", "expected %n to always be called with match %*%C");
mirrorPropAsAssertion("calledWithExactly", "expected %n to be called with exact arguments %*%C");
mirrorPropAsAssertion("alwaysCalledWithExactly", "expected %n to always be called with exact arguments %*%C");
mirrorPropAsAssertion("neverCalledWith", "expected %n to never be called with arguments %*%C");
mirrorPropAsAssertion("neverCalledWithMatch", "expected %n to never be called with match %*%C");
mirrorPropAsAssertion("threw", "%n did not throw exception%C");

@@ -165,0 +170,0 @@ mirrorPropAsAssertion("alwaysThrew", "%n did not always throw exception%C");

@@ -109,3 +109,14 @@ /**

}
if (!property && !!object && typeof object == "object") {
var stubbedObj = sinon.stub.apply(sinon, arguments);
for (var prop in stubbedObj) {
if (typeof stubbedObj[prop] === "function") {
this.add(stubbedObj[prop]);
}
}
return stubbedObj;
}
return this.add(sinon.stub.apply(sinon, arguments));

@@ -112,0 +123,0 @@ },

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

sinon.expectation.fail(messages.concat(met).join("\n"));
} else {
sinon.expectation.pass(messages.concat(met).join("\n"));
}

@@ -126,5 +128,5 @@

var expectations = this.expectations && this.expectations[method];
var length = expectations && expectations.length || 0;
var length = expectations && expectations.length || 0, i;
for (var i = 0; i < length; i += 1) {
for (i = 0; i < length; i += 1) {
if (!expectations[i].met() &&

@@ -136,8 +138,17 @@ expectations[i].allowsCall(thisValue, args)) {

var messages = [];
var messages = [], available, exhausted = 0;
for (i = 0; i < length; i += 1) {
if (expectations[i].allowsCall(thisValue, args)) {
available = available || expectations[i];
} else {
exhausted += 1;
}
push.call(messages, " " + expectations[i].toString());
}
if (exhausted === 0) {
return available.apply(thisValue, args);
}
messages.unshift("Unexpected call: " + sinon.spyCall.toString.call({

@@ -293,3 +304,3 @@ proxy: method,

if (!args || args.length === 0) {
if (!args) {
sinon.expectation.fail(this.method + " received no arguments, expected " +

@@ -319,3 +330,3 @@ this.expectedArguments.join());

allowsCall: function allowsCall(thisValue, args) {
if (this.met()) {
if (this.met() && receivedMaxCalls(this)) {
return false;

@@ -393,2 +404,4 @@ }

sinon.expectation.fail(this.toString());
} else {
sinon.expectation.pass(this.toString());
}

@@ -399,2 +412,5 @@

pass: function(message) {
sinon.assert.pass(message);
},
fail: function (message) {

@@ -401,0 +417,0 @@ var exception = new Error(message);

50

lib/sinon/spy.js

@@ -1,2 +0,5 @@

/* @depend ../sinon.js */
/**
* @depend ../sinon.js
* @depend match.js
*/
/*jslint eqeqeq: false, onevar: false, plusplus: false*/

@@ -34,3 +37,3 @@ /*global module, require, sinon*/

if (!object || !property) {
if (!object && !property) {
return spy.create(function () {});

@@ -90,2 +93,3 @@ }

this.callCount += 1;
this.notCalled = false;
this.calledOnce = this.callCount == 1;

@@ -109,2 +113,3 @@ this.calledTwice = this.callCount == 2;

this.called = false;
this.notCalled = true;
this.calledOnce = false;

@@ -123,2 +128,7 @@ this.calledTwice = false;

this.callIds = [];
if (this.fakes) {
for (var i = 0; i < this.fakes.length; i++) {
this.fakes[i].reset();
}
}
},

@@ -281,3 +291,5 @@

delegateToCalls(spyApi, "calledWith", true);
delegateToCalls(spyApi, "calledWithMatch", true);
delegateToCalls(spyApi, "alwaysCalledWith", false, "calledWith");
delegateToCalls(spyApi, "alwaysCalledWithMatch", false, "calledWithMatch");
delegateToCalls(spyApi, "calledWithExactly", true);

@@ -287,2 +299,4 @@ delegateToCalls(spyApi, "alwaysCalledWithExactly", false, "calledWithExactly");

function () { return true; });
delegateToCalls(spyApi, "neverCalledWithMatch", false, "notCalledWithMatch",
function () { return true; });
delegateToCalls(spyApi, "threw", true);

@@ -338,3 +352,9 @@ delegateToCalls(spyApi, "alwaysThrew", false, "threw");

"*": function (spy, args) {
return args.join(", ");
var formatted = [];
for (var i = 0, l = args.length; i < l; ++i) {
push.call(formatted, sinon.format(args[i]));
}
return formatted.join(", ");
}

@@ -384,2 +404,13 @@ };

calledWithMatch: function calledWithMatch() {
for (var i = 0, l = arguments.length; i < l; i += 1) {
var actual = this.args[i];
var expectation = arguments[i];
if (!sinon.match || !sinon.match(expectation).test(actual)) {
return false;
}
}
return true;
},
calledWithExactly: function calledWithExactly() {

@@ -391,12 +422,11 @@ return arguments.length == this.args.length &&

notCalledWith: function notCalledWith() {
for (var i = 0, l = arguments.length; i < l; i += 1) {
if (!sinon.deepEqual(arguments[i], this.args[i])) {
return true;
}
}
return false;
return !this.calledWith.apply(this, arguments);
},
notCalledWithMatch: function notCalledWithMatch() {
return !this.calledWithMatch.apply(this, arguments);
},
returned: function returned(value) {
return this.returnValue === value;
return sinon.deepEqual(value, this.returnValue);
},

@@ -403,0 +433,0 @@

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

var nextTick = (function () {
if (typeof process === "object" && typeof process.nextTick === "function") {
return process.nextTick;
} else if (typeof msSetImmediate === "function") {
return msSetImmediate.bind(window);
} else if (typeof setImmediate === "function") {
return setImmediate;
} else {
return function (callback) {
setTimeout(callback, 0);
};
}
})();
function callCallback(stub, args) {

@@ -111,3 +125,9 @@ if (typeof stub.callArgAt == "number") {

func.apply(stub.callbackContext, stub.callbackArguments);
if (stub.callbackAsync) {
nextTick(function() {
func.apply(stub.callbackContext, stub.callbackArguments);
});
} else {
func.apply(stub.callbackContext, stub.callbackArguments);
}
}

@@ -119,3 +139,3 @@ }

sinon.extend(stub, (function () {
var slice = Array.prototype.slice;
var slice = Array.prototype.slice, proto;

@@ -131,9 +151,12 @@ function throwsException(error, message) {

}
return this;
}
return {
proto = {
create: function create() {
var functionStub = function () {
callCallback(functionStub, arguments);
if (functionStub.exception) {

@@ -143,6 +166,5 @@ throw functionStub.exception;

return arguments[functionStub.returnArgAt];
} else if (functionStub.returnThis) {
return this;
}
callCallback(functionStub, arguments);
return functionStub.returnValue;

@@ -174,3 +196,3 @@ };

}
this.returnArgAt = pos;

@@ -181,2 +203,8 @@

returnsThis: function returnsThis() {
this.returnThis = true;
return this;
},
"throws": throwsException,

@@ -277,2 +305,17 @@ throwsException: throwsException,

};
// create asynchronous versions of callsArg* and yields* methods
for (var method in proto) {
if (proto.hasOwnProperty(method) && method.match(/^(callsArg|yields)/)) {
proto[method + 'Async'] = (function (syncFnName) {
return function () {
this.callbackAsync = true;
return this[syncFnName].apply(this, arguments);
};
})(method);
}
}
return proto;
}()));

@@ -279,0 +322,0 @@

@@ -47,3 +47,3 @@ /**

var wloc = window.location;
var wloc = typeof window !== "undefined" ? window.location : {};
var rCurrLoc = new RegExp("^" + wloc.protocol + "//" + wloc.host);

@@ -50,0 +50,0 @@

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

func: args[0],
callAt: this.now + delay
callAt: this.now + delay,
invokeArgs: Array.prototype.slice.call(args, 2)
};

@@ -179,3 +180,4 @@

interval: this.timeouts[id].interval,
id: this.timeouts[id].id
id: this.timeouts[id].id,
invokeArgs: this.timeouts[id].invokeArgs
};

@@ -190,5 +192,11 @@ }

callTimer: function (timer) {
if (typeof timer.interval == "number") {
this.timeouts[timer.id].callAt += timer.interval;
} else {
delete this.timeouts[timer.id];
}
try {
if (typeof timer.func == "function") {
timer.func.call(null);
timer.func.apply(null, timer.invokeArgs);
} else {

@@ -208,8 +216,2 @@ eval(timer.func);

if (typeof timer.interval == "number") {
this.timeouts[timer.id].callAt += timer.interval;
} else {
delete this.timeouts[timer.id];
}
if (exception) {

@@ -290,7 +292,15 @@ throw exception;

method = this.methods[i];
global[method] = this["_" + method];
if (global[method].hadOwnProperty) {
global[method] = this["_" + method];
} else {
delete global[method];
}
}
// Prevent multiple executions which will completely remove these props
this.methods = [];
}
function stubGlobal(method, clock) {
clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(global, method);
clock["_" + method] = global[method];

@@ -297,0 +307,0 @@

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

@@ -20,4 +20,17 @@ "author": "Christian Johansen",

],
"scripts": {
"test": "node test/node/run.js"
},
"dependencies": {
"buster-format": "~0.5"
},
"devDependencies": {
"buster-core": "~0.6",
"buster-assertions": "~0.10",
"buster-evented-logger": "~0.4",
"buster-test": "~0.5",
"http-server": "*"
},
"main": "./lib/sinon.js",
"engines": { "node": ">=0.1.103" }
}
/**
* Sinon.JS 1.3.3, 2012/04/16
* Sinon.JS 1.4.0, 2012/07/09
*
* @author Christian Johansen (christian@cjohansen.no)
* @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS
*
* (The BSD License)
*
* Copyright (c) 2010-2011, Christian Johansen, christian@cjohansen.no
* Copyright (c) 2010-2012, Christian Johansen, christian@cjohansen.no
* All rights reserved.

@@ -10,0 +11,0 @@ *

# Sinon.JS
[![Build status](https://secure.travis-ci.org/cjohansen/Sinon.JS.png?branch=master)](http://travis-ci.org/cjohansen/Sinon.JS)
Standalone and test framework agnostic JavaScript test spies, stubs and mocks.
## Installation
## Installation

@@ -11,3 +13,3 @@ via [npm (node package manager)](http://github.com/isaacs/npm)

or install via git by cloning the repository and including sinon.js
or install via git by cloning the repository and including sinon.js
in your project, as you would any other third party library.

@@ -31,14 +33,39 @@

## Develop?
## Contribute?
Check out [todo.org](http://github.com/cjohansen/Sinon.JS/raw/1.0.0/todo.org) in the project repository
Pick [an issue](http://github.com/cjohansen/Sinon.JS/issues) to fix, or pitch
new features. To avoid wasting your time, please ask for feedback on feature
suggestions either with [an issue](http://github.com/cjohansen/Sinon.JS/issues/new)
or on [the mailing list](http://groups.google.com/group/sinonjs).
## Running tests on Rhino
## Run the tests
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):
The Sinon.JS developer environment requires Node/NPM. Please make sure you have
Node installed, and install Sinon's dependencies:
$ java -jar js.jar -opt -1 test/rhino/run.js
$ npm install
### On Node
$ npm test
### In the browser
Open `test/sinon.html` in a browser. To test against a built distribution, first
make sure you have a build (requires Ruby and Juicer):
$ ./build
Then open `test/sinon-dist.html` in a browser.
Some tests needs working XHR to pass. To run the tests over an HTTP server, run
$ node_modules/http-server/bin/http-server
Then open [localhost:8080/test/sinon.html](http://localhost:8080/test/sinon.html)
in a browser.
### On Rhino
The Rhino tests are currently out of commission (pending update after switch to
Buster.JS for tests).

@@ -1,4 +0,1 @@

global.jstestdriver = { console: console };
global.window = {};
require("../sinon_test.js");

@@ -14,1 +11,13 @@ require("../sinon/spy_test.js");

require("../sinon/test_case_test.js");
require("../sinon/match_test.js");
var buster = require("../runner");
buster.testRunner.onCreate(function (runner) {
runner.on("suite:end", function (results) {
// Reporter will be set up after delay, allow
// it to finish before we exit the process
process.nextTick(function () {
process.exit(results.ok ? 0 : 1);
});
});
});

@@ -16,2 +16,3 @@ var jstestdriver = {};

load("lib/sinon/test.js");
load("lib/sinon/match.js");
load("lib/sinon/util/fake_server.js");

@@ -32,2 +33,3 @@ load("lib/sinon/util/fake_server_with_clock.js");

load("test/sinon/test_test.js");
load("test/sinon/match_test.js");
load("test/sinon/util/fake_server_test.js");

@@ -34,0 +36,0 @@ load("test/sinon/util/fake_server_with_clock_test.js");

/*jslint onevar: false, eqeqeq: false*/
/*globals testCase
document
sinon
fail
assert
assertFalse
assertEquals
assertSame
assertNotSame
assertFunction
assertObject
assertException
assertNoException*/
/*globals document sinon buster*/
/**

@@ -19,19 +7,13 @@ * @author Christian Johansen (christian@cjohansen.no)

*
* Copyright (c) 2010-2011 Christian Johansen
* Copyright (c) 2010-2012 Christian Johansen
*/
"use strict";
if (typeof require == "function" && typeof testCase == "undefined") {
var testCase = require("./test_case_shim");
if (typeof require == "function" && typeof module == "object") {
var buster = require("./runner");
var sinon = require("../lib/sinon");
}
(function () {
testCase("SinonTest", {
"sinon should be object": function () {
assertObject(sinon);
}
});
testCase("SinonWrapMethodTest", {
buster.testCase("sinon", {
".wrapMethod": {
setUp: function () {

@@ -42,8 +24,8 @@ this.method = function () {};

"should be function": function () {
assertFunction(sinon.wrapMethod);
"is function": function () {
assert.isFunction(sinon.wrapMethod);
},
"should throw if first argument is not object": function () {
assertException(function () {
"throws if first argument is not object": function () {
assert.exception(function () {
sinon.wrapMethod();

@@ -53,7 +35,7 @@ }, "TypeError");

"should throw if object defines property but is not function": function () {
"throws if object defines property but is not function": function () {
this.object.prop = 42;
var object = this.object;
assertException(function () {
assert.exception(function () {
sinon.wrapMethod(object, "prop", function () {});

@@ -63,6 +45,6 @@ }, "TypeError");

"should throw if object does not define property": function () {
"throws if object does not define property": function () {
var object = this.object;
assertException(function () {
assert.exception(function () {
sinon.wrapMethod(object, "prop", function () {});

@@ -72,6 +54,6 @@ });

"should throw if third argument is missing": function () {
"throws if third argument is missing": function () {
var object = this.object;
assertException(function () {
assert.exception(function () {
sinon.wrapMethod(object, "method");

@@ -81,6 +63,6 @@ }, "TypeError");

"should throw if third argument is not function": function () {
"throws if third argument is not function": function () {
var object = this.object;
assertException(function () {
assert.exception(function () {
sinon.wrapMethod(object, "method", {});

@@ -90,14 +72,14 @@ }, "TypeError");

"should replace object method": function () {
"replaces object method": function () {
sinon.wrapMethod(this.object, "method", function () {});
assertNotSame(this.method, this.object.method);
assertFunction(this.object.method);
refute.same(this.method, this.object.method);
assert.isFunction(this.object.method);
},
"should throw if method is already wrapped": function () {
"throws if method is already wrapped": function () {
var object = { method: function () {} };
sinon.wrapMethod(object, "method", function () {});
assertException(function () {
assert.exception(function () {
sinon.wrapMethod(object, "method", function () {});

@@ -107,6 +89,6 @@ }, "TypeError");

"should throw if method is already a spy": function () {
"throws if method is already a spy": function () {
var object = { method: sinon.spy() };
assertException(function () {
assert.exception(function () {
sinon.wrapMethod(object, "method", function () {});

@@ -116,15 +98,21 @@ }, "TypeError");

"should not throw if object is window object": function () {
window.sinonTestMethod = function () {};
try {
assertNoException(function () {
sinon.wrapMethod(window, "sinonTestMethod", function () {});
});
} finally {
// IE 8 does not support delete on global properties.
window.sinonTestMethod = undefined;
"in browser": {
requiresSupportFor: {
"window object": typeof window !== "undefined"
},
"does not throw if object is window object": function () {
window.sinonTestMethod = function () {};
try {
refute.exception(function () {
sinon.wrapMethod(window, "sinonTestMethod", function () {});
});
} finally {
// IE 8 does not support delete on global properties.
window.sinonTestMethod = undefined;
}
}
},
"should mirror function properties": function () {
"mirrors function properties": function () {
var object = { method: function () {} };

@@ -135,6 +123,6 @@ object.method.prop = 42;

assertEquals(42, object.method.prop);
assert.equals(object.method.prop, 42);
},
"should not mirror and overwrite existing properties": function () {
"does not mirror and overwrite existing properties": function () {
var object = { method: function () {} };

@@ -145,7 +133,7 @@ object.method.called = 42;

assertSame(false, object.method.called);
assert.isFalse(object.method.called);
}
});
},
testCase("WrappedMethodTest", {
"wrapped method": {
setUp: function () {

@@ -156,23 +144,23 @@ this.method = function () {};

"should define restore method": function () {
"defines restore method": function () {
sinon.wrapMethod(this.object, "method", function () {});
assertFunction(this.object.method.restore);
assert.isFunction(this.object.method.restore);
},
"should return wrapper": function () {
"returns wrapper": function () {
var wrapper = sinon.wrapMethod(this.object, "method", function () {});
assertSame(wrapper, this.object.method);
assert.same(this.object.method, wrapper);
},
"restore should bring back original method": function () {
"restore brings back original method": function () {
sinon.wrapMethod(this.object, "method", function () {});
this.object.method.restore();
assertSame(this.method, this.object.method);
assert.same(this.object.method, this.method);
}
});
},
testCase("WrappedPrototypeMethodTest", {
"wrapped prototype method": {
setUp: function () {

@@ -184,52 +172,52 @@ this.type = function () {};

"wrap should add owned property": function () {
"wrap adds owned property": function () {
var wrapper = sinon.wrapMethod(this.object, "method", function () {});
assertSame(wrapper, this.object.method);
assert.same(this.object.method, wrapper);
assert(this.object.hasOwnProperty("method"));
},
"restore should remove owned property": function () {
"restore removes owned property": function () {
sinon.wrapMethod(this.object, "method", function () {});
this.object.method.restore();
assertSame(this.type.prototype.method, this.object.method);
assertFalse(this.object.hasOwnProperty("method"));
assert.same(this.object.method, this.type.prototype.method);
assert.isFalse(this.object.hasOwnProperty("method"));
}
});
},
testCase("SinonDeepEqualTest", {
"should pass null": function () {
"deepEqual": {
"passes null": function () {
assert(sinon.deepEqual(null, null));
},
"should not pass null and object": function () {
assertFalse(sinon.deepEqual(null, {}));
"fails null and object": function () {
assert.isFalse(sinon.deepEqual(null, {}));
},
"should not pass object and null": function () {
assertFalse(sinon.deepEqual({}, null));
"fails object and null": function () {
assert.isFalse(sinon.deepEqual({}, null));
},
"should not pass error and object": function () {
assertFalse(sinon.deepEqual(new Error(), {}));
"fails error and object": function () {
assert.isFalse(sinon.deepEqual(new Error(), {}));
},
"should not pass object and error": function () {
assertFalse(sinon.deepEqual({}, new Error()));
"fails object and error": function () {
assert.isFalse(sinon.deepEqual({}, new Error()));
},
"should not pass regexp and object": function () {
assertFalse(sinon.deepEqual(/.*/, {}));
"fails regexp and object": function () {
assert.isFalse(sinon.deepEqual(/.*/, {}));
},
"should not pass object and regexp": function () {
assertFalse(sinon.deepEqual({}, /.*/));
"fails object and regexp": function () {
assert.isFalse(sinon.deepEqual({}, /.*/));
},
"should pass primitives": function () {
"passes primitives": function () {
assert(sinon.deepEqual(1, 1));
},
"should pass same object": function () {
"passes same object": function () {
var object = {};

@@ -240,3 +228,3 @@

"should pass same function": function () {
"passes same function": function () {
var func = function () {};

@@ -247,3 +235,3 @@

"should pass same array": function () {
"passes same array": function () {
var arr = [];

@@ -254,3 +242,3 @@

"should pass equal arrays": function () {
"passes equal arrays": function () {
var arr1 = [1, 2, 3, "hey", "there"];

@@ -262,3 +250,3 @@ var arr2 = [1, 2, 3, "hey", "there"];

"should pass equal objects": function () {
"passes equal objects": function () {
var obj1 = { a: 1, b: 2, c: 3, d: "hey", e: "there" };

@@ -270,28 +258,31 @@ var obj2 = { b: 2, c: 3, a: 1, d: "hey", e: "there" };

"should pass same DOM elements": function () {
/*:DOC element = <div class="hey"></div> */
if (typeof document == "undefined") return console.log("Test requires DOM");
"in browsers": {
requiresSupportFor: {
"document object": typeof document !== "undefined"
},
assert(sinon.deepEqual(this.element, this.element));
},
"passes same DOM elements": function () {
var element = document.createElement("div");
"should not pass different DOM elements": function () {
/*:DOC element = <div class="hey"></div> */
if (typeof document == "undefined") return console.log("Test requires DOM");
var el = document.createElement("div");
assert(sinon.deepEqual(element, element));
},
assertFalse(sinon.deepEqual(this.element, el));
},
"fails different DOM elements": function () {
var element = document.createElement("div");
var el = document.createElement("div");
"should not modify DOM elements when comparing them": function () {
/*:DOC += <div id="hey"></div> */
if (typeof document == "undefined") return console.log("Test requires DOM");
var el = document.getElementById("hey");
sinon.deepEqual(el, {})
assert.isFalse(sinon.deepEqual(element, el));
},
assertSame(document.body, el.parentNode);
assertEquals(0, el.childNodes.length);
"does not modify DOM elements when comparing them": function () {
var el = document.createElement("div");
document.body.appendChild(el);
sinon.deepEqual(el, {});
assert.same(el.parentNode, document.body);
assert.equals(el.childNodes.length, 0);
}
},
"should pass deep objects": function () {
"passes deep objects": function () {
var func = function () {};

@@ -329,6 +320,6 @@

}
});
},
testCase("ExtendTest", {
"should copy all properties": function () {
"extend": {
"copies all properties": function () {
var object1 = {

@@ -353,15 +344,15 @@ prop1: null,

assertEquals(expected, result);
assert.equals(result, expected);
}
});
},
testCase("FunctionToStringTest", {
"should return function's displayName property": function () {
"Function.prototype.toString": {
"returns function's displayName property": function () {
var fn = function () {};
fn.displayName = "Larry";
assertEquals("Larry", sinon.functionToString.call(fn));
assert.equals(sinon.functionToString.call(fn), "Larry");
},
"should guess name from last call's this object": function () {
"guesses name from last call's this object": function () {
var obj = {};

@@ -372,6 +363,6 @@ obj.doStuff = sinon.spy();

assertEquals("doStuff", sinon.functionToString.call(obj.doStuff));
assert.equals(sinon.functionToString.call(obj.doStuff), "doStuff");
},
"should guess name from any call where property can be located": function () {
"guesses name from any call where property can be located": function () {
var obj = {}, otherObj = { id: 42 };

@@ -383,16 +374,16 @@ obj.doStuff = sinon.spy();

assertEquals("doStuff", sinon.functionToString.call(obj.doStuff));
assert.equals(sinon.functionToString.call(obj.doStuff), "doStuff");
}
});
},
testCase("ConfigTest", {
"should get copy of default config": function () {
"config": {
"gets copy of default config": function () {
var config = sinon.getConfig();
assertNotSame(sinon.defaultConfig, config);
assertEquals(sinon.defaultConfig.injectIntoThis, config.injectIntoThis);
assertEquals(sinon.defaultConfig.injectInto, config.injectInto);
assertEquals(sinon.defaultConfig.properties, config.properties);
assertEquals(sinon.defaultConfig.useFakeTimers, config.useFakeTimers);
assertEquals(sinon.defaultConfig.useFakeServer, config.useFakeServer);
refute.same(config, sinon.defaultConfig);
assert.equals(config.injectIntoThis, sinon.defaultConfig.injectIntoThis);
assert.equals(config.injectInto, sinon.defaultConfig.injectInto);
assert.equals(config.properties, sinon.defaultConfig.properties);
assert.equals(config.useFakeTimers, sinon.defaultConfig.useFakeTimers);
assert.equals(config.useFakeServer, sinon.defaultConfig.useFakeServer);
},

@@ -406,26 +397,70 @@

assertNotSame(sinon.defaultConfig, config);
assertEquals(sinon.defaultConfig.injectIntoThis, config.injectIntoThis);
assertEquals(sinon.defaultConfig.injectInto, config.injectInto);
assertEquals(["stub", "mock"], config.properties);
assertEquals(sinon.defaultConfig.useFakeTimers, config.useFakeTimers);
assertEquals(false, config.useFakeServer);
refute.same(config, sinon.defaultConfig);
assert.equals(config.injectIntoThis, sinon.defaultConfig.injectIntoThis);
assert.equals(config.injectInto, sinon.defaultConfig.injectInto);
assert.equals(config.properties, ["stub", "mock"]);
assert.equals(config.useFakeTimers, sinon.defaultConfig.useFakeTimers);
assert.isFalse(config.useFakeServer);
}
});
},
testCase("LogTest", {
"should do nothing gracefully": function () {
sinon.log("Oh, hiya");
"log": {
"does nothing gracefully": function () {
refute.exception(function () {
sinon.log("Oh, hiya");
});
}
});
},
testCase("FormatTest", {
"should format with buster by default": function () {
assertEquals("{ id: 42 }", sinon.format({ id: 42 }));
"format": {
"formats with buster by default": function () {
assert.equals(sinon.format({ id: 42 }), "{ id: 42 }");
},
"should format strings without quotes": function () {
assertEquals("Hey", sinon.format("Hey"));
"formats strings without quotes": function () {
assert.equals(sinon.format("Hey"), "Hey");
}
});
}());
},
"typeOf": {
"returns boolean": function () {
assert.equals(sinon.typeOf(false), "boolean");
},
"returns string": function () {
assert.equals(sinon.typeOf("Sinon.JS"), "string");
},
"returns number": function () {
assert.equals(sinon.typeOf(123), "number");
},
"returns object": function () {
assert.equals(sinon.typeOf({}), "object");
},
"returns function": function () {
assert.equals(sinon.typeOf(function () {}), "function");
},
"returns undefined": function () {
assert.equals(sinon.typeOf(undefined), "undefined");
},
"returns null": function () {
assert.equals(sinon.typeOf(null), "null");
},
"returns array": function () {
assert.equals(sinon.typeOf([]), "array");
},
"returns regexp": function () {
assert.equals(sinon.typeOf(/.*/), "regexp");
},
"returns date": function () {
assert.equals(sinon.typeOf(new Date()), "date");
}
}
});
/*jslint onevar: false*/
/*globals testCase
sinon
fail
failException
assert
assertString
assertFunction
assertObject
assertFalse
assertEquals
assertNoException
assertException
assertCalled
assertCalledOn
assertCalledWith
assertCalledWithExactly
assertThrew
assertCallCount*/
/*globals sinon buster*/
/**

@@ -24,30 +7,32 @@ * @author Christian Johansen (christian@cjohansen.no)

*
* Copyright (c) 2010-2011 Christian Johansen
* Copyright (c) 2010-2012 Christian Johansen
*/
"use strict";
if (typeof require == "function" && typeof testCase == "undefined") {
var testCase = require("../test_case_shim");
if (typeof require == "function" && typeof module == "object") {
var buster = require("../runner");
var sinon = require("../../lib/sinon");
}
(function (global) {
testCase("SinonAssertTest", {
"should be object": function () {
assertObject(sinon.assert);
}
});
buster.testCase("sinon.assert", {
setUp: function () {
this.global = typeof window !== "undefined" ? window : global;
function stubSetUp() {
this.stub = sinon.stub.create();
sinon.stub(sinon.assert, "fail").throws();
sinon.stub(sinon.assert, "pass");
}
this.setUpStubs = function () {
this.stub = sinon.stub.create();
sinon.stub(sinon.assert, "fail").throws();
sinon.stub(sinon.assert, "pass");
};
function stubTearDown() {
sinon.assert.fail.restore();
sinon.assert.pass.restore();
}
this.tearDownStubs = function () {
sinon.assert.fail.restore();
sinon.assert.pass.restore();
};
},
testCase("SinonAssertFailTest", {
"is object": function () {
assert.isObject(sinon.assert);
},
"fail": {
setUp: function () {

@@ -61,3 +46,3 @@ this.exceptionName = sinon.assert.failException;

"should throw exception": function () {
"throws exception": function () {
var failed = false;

@@ -73,25 +58,21 @@ var exception;

assertFalse(failed);
assertEquals("AssertError", exception.name);
assert.isFalse(failed);
assert.equals(exception.name, "AssertError");
},
"should throw configured exception type": function () {
"throws configured exception type": function () {
sinon.assert.failException = "RetardError";
assertException(function () {
assert.exception(function () {
sinon.assert.fail("Some message");
}, "RetardError");
}
});
},
testCase("SinonAssertCalledTest", {
setUp: stubSetUp,
tearDown: stubTearDown,
"called": {
setUp: function () { this.setUpStubs(); },
tearDown: function () { this.tearDownStubs(); },
"should be function": function () {
assertFunction(sinon.assert.called);
},
"should fail when method does not exist": function () {
assertException(function () {
"fails when method does not exist": function () {
assert.exception(function () {
sinon.assert.called();

@@ -103,4 +84,4 @@ });

"should fail when method is not stub": function () {
assertException(function () {
"fails when method is not stub": function () {
assert.exception(function () {
sinon.assert.called(function () {});

@@ -112,6 +93,6 @@ });

"should fail when method was not called": function () {
"fails when method was not called": function () {
var stub = this.stub;
assertException(function () {
assert.exception(function () {
sinon.assert.called(stub);

@@ -123,18 +104,18 @@ });

"should not fail when method was called": function () {
"does not fail when method was called": function () {
var stub = this.stub;
stub();
assertNoException(function () {
refute.exception(function () {
sinon.assert.called(stub);
});
assertFalse(sinon.assert.fail.called);
assert.isFalse(sinon.assert.fail.called);
},
"should call pass callback": function () {
"calls pass callback": function () {
var stub = this.stub;
stub();
assertNoException(function () {
refute.exception(function () {
sinon.assert.called(stub);

@@ -146,14 +127,10 @@ });

}
});
},
testCase("SinonAssertNotCalledTest", {
setUp: stubSetUp,
tearDown: stubTearDown,
"notCalled": {
setUp: function () { this.setUpStubs(); },
tearDown: function () { this.tearDownStubs(); },
"should be function": function () {
assertFunction(sinon.assert.notCalled);
},
"should fail when method does not exist": function () {
assertException(function () {
"fails when method does not exist": function () {
assert.exception(function () {
sinon.assert.notCalled();

@@ -165,4 +142,4 @@ });

"should fail when method is not stub": function () {
assertException(function () {
"fails when method is not stub": function () {
assert.exception(function () {
sinon.assert.notCalled(function () {});

@@ -174,7 +151,7 @@ });

"should fail when method was called": function () {
"fails when method was called": function () {
var stub = this.stub;
stub();
assertException(function () {
assert.exception(function () {
sinon.assert.notCalled(stub);

@@ -186,10 +163,10 @@ });

"should not fail when method was not called": function () {
"passes when method was not called": function () {
var stub = this.stub;
assertNoException(function () {
refute.exception(function () {
sinon.assert.notCalled(stub);
});
assertFalse(sinon.assert.fail.called);
assert.isFalse(sinon.assert.fail.called);
},

@@ -204,14 +181,10 @@

}
});
},
testCase("SinonAssertCalledOnceTest", {
setUp: stubSetUp,
tearDown: stubTearDown,
"calledOnce": {
setUp: function () { this.setUpStubs(); },
tearDown: function () { this.tearDownStubs(); },
"should be function": function () {
assertFunction(sinon.assert.calledOnce);
},
"should fail when method does not exist": function () {
assertException(function () {
"fails when method does not exist": function () {
assert.exception(function () {
sinon.assert.calledOnce();

@@ -223,4 +196,4 @@ });

"should fail when method is not stub": function () {
assertException(function () {
"fails when method is not stub": function () {
assert.exception(function () {
sinon.assert.calledOnce(function () {});

@@ -232,6 +205,6 @@ });

"should fail when method was not called": function () {
"fails when method was not called": function () {
var stub = this.stub;
assertException(function () {
assert.exception(function () {
sinon.assert.calledOnce(stub);

@@ -243,14 +216,14 @@ });

"should not fail when method was called": function () {
"passes when method was called": function () {
var stub = this.stub;
stub();
assertNoException(function () {
refute.exception(function () {
sinon.assert.calledOnce(stub);
});
assertFalse(sinon.assert.fail.called);
assert.isFalse(sinon.assert.fail.called);
},
"should fail when method was called more than once": function () {
"fails when method was called more than once": function () {
var stub = this.stub;

@@ -260,3 +233,3 @@ stub();

assertException(function () {
assert.exception(function () {
sinon.assert.calledOnce(stub);

@@ -268,3 +241,3 @@ });

"should call pass callback": function () {
"calls pass callback": function () {
var stub = this.stub;

@@ -277,13 +250,13 @@ stub();

}
});
},
testCase("SinonAssertCalledTwiceTest", {
setUp: stubSetUp,
tearDown: stubTearDown,
"calledTwice": {
setUp: function () { this.setUpStubs(); },
tearDown: function () { this.tearDownStubs(); },
"should fail if called once": function () {
"fails if called once": function () {
var stub = this.stub;
this.stub();
assertException(function () {
assert.exception(function () {
sinon.assert.calledTwice(stub);

@@ -293,3 +266,3 @@ });

"should not fail if called twice": function () {
"passes if called twice": function () {
var stub = this.stub;

@@ -299,3 +272,3 @@ this.stub();

assertNoException(function () {
refute.exception(function () {
sinon.assert.calledTwice(stub);

@@ -305,3 +278,3 @@ });

"should call pass callback": function () {
"calls pass callback": function () {
var stub = this.stub;

@@ -315,13 +288,13 @@ stub();

}
});
},
testCase("SinonAssertCalledThriceTest", {
setUp: stubSetUp,
tearDown: stubTearDown,
"calledThrice": {
setUp: function () { this.setUpStubs(); },
tearDown: function () { this.tearDownStubs(); },
"should fail if called once": function () {
"fails if called once": function () {
var stub = this.stub;
this.stub();
assertException(function () {
assert.exception(function () {
sinon.assert.calledThrice(stub);

@@ -331,3 +304,3 @@ });

"should not fail if called thrice": function () {
"passes if called thrice": function () {
var stub = this.stub;

@@ -338,3 +311,3 @@ this.stub();

assertNoException(function () {
refute.exception(function () {
sinon.assert.calledThrice(stub);

@@ -344,3 +317,3 @@ });

"should call pass callback": function () {
"calls pass callback": function () {
var stub = this.stub;

@@ -355,13 +328,9 @@ stub();

}
});
},
testCase("SinonAssertCallOrderTest", {
setUp: stubSetUp,
tearDown: stubTearDown,
"callOrder": {
setUp: function () { this.setUpStubs(); },
tearDown: function () { this.tearDownStubs(); },
"should be function": function () {
assertFunction(sinon.assert.callOrder);
},
"should not fail when calls where done in right order": function () {
"passes when calls where done in right order": function () {
var spy1 = sinon.spy();

@@ -372,3 +341,3 @@ var spy2 = sinon.spy();

assertNoException(function () {
refute.exception(function () {
sinon.assert.callOrder(spy1, spy2);

@@ -378,3 +347,3 @@ });

"should fail when calls where done in wrong order": function () {
"fails when calls where done in wrong order": function () {
var spy1 = sinon.spy();

@@ -385,3 +354,3 @@ var spy2 = sinon.spy();

assertException(function () {
assert.exception(function () {
sinon.assert.callOrder(spy1, spy2);

@@ -393,3 +362,3 @@ });

"should not fail when many calls where done in right order": function () {
"passes when many calls where done in right order": function () {
var spy1 = sinon.spy();

@@ -404,3 +373,3 @@ var spy2 = sinon.spy();

assertNoException(function () {
refute.exception(function () {
sinon.assert.callOrder(spy1, spy2, spy3, spy4);

@@ -410,3 +379,3 @@ });

"should fail when one of many calls where done in wrong order": function () {
"fails when one of many calls where done in wrong order": function () {
var spy1 = sinon.spy();

@@ -421,3 +390,3 @@ var spy2 = sinon.spy();

assertException(function () {
assert.exception(function () {
sinon.assert.callOrder(spy1, spy2, spy3, spy4);

@@ -429,3 +398,3 @@ });

"should call pass callback": function () {
"calls pass callback": function () {
var stubs = [sinon.spy(), sinon.spy()];

@@ -440,3 +409,3 @@ stubs[0]();

"should pass for multiple calls to same spy": function () {
"passes for multiple calls to same spy": function () {
var first = sinon.spy();

@@ -449,39 +418,37 @@ var second = sinon.spy();

sinon.assert.callOrder(first, second, first);
refute.exception(function () {
sinon.assert.callOrder(first, second, first);
});
}
});
},
testCase("SinonAssertCalledOnTest", {
setUp: stubSetUp,
tearDown: stubTearDown,
"calledOn": {
setUp: function () { this.setUpStubs(); },
tearDown: function () { this.tearDownStubs(); },
"should be function": function () {
assertFunction(sinon.assert.calledOn);
},
"should fail when method does not exist": function () {
"fails when method does not exist": function () {
var object = {};
sinon.stub(this.stub, "calledOn");
assertException(function () {
assert.exception(function () {
sinon.assert.calledOn(null, object);
});
assertFalse(this.stub.calledOn.calledWith(object));
assert.isFalse(this.stub.calledOn.calledWith(object));
assert(sinon.assert.fail.called);
},
"should fail when method is not stub": function () {
"fails when method is not stub": function () {
var object = {};
sinon.stub(this.stub, "calledOn");
assertException(function () {
assert.exception(function () {
sinon.assert.calledOn(function () {}, object);
});
assertFalse(this.stub.calledOn.calledWith(object));
assert.isFalse(this.stub.calledOn.calledWith(object));
assert(sinon.assert.fail.called);
},
"should fail when method fails": function () {
"fails when method fails": function () {
var object = {};

@@ -491,3 +458,3 @@ sinon.stub(this.stub, "calledOn").returns(false);

assertException(function () {
assert.exception(function () {
sinon.assert.calledOn(stub, object);

@@ -499,3 +466,3 @@ });

"should not fail when method doesn't fail": function () {
"passes when method doesn't fail": function () {
var object = {};

@@ -507,6 +474,6 @@ sinon.stub(this.stub, "calledOn").returns(true);

assertFalse(sinon.assert.fail.called);
assert.isFalse(sinon.assert.fail.called);
},
"should call pass callback": function () {
"calls pass callback": function () {
var obj = {};

@@ -519,9 +486,119 @@ this.stub.call(obj);

}
});
},
testCase("SinonAssertCalledWithTest", {
setUp: stubSetUp,
tearDown: stubTearDown,
"calledWithNew": {
setUp: function () { this.setUpStubs(); },
tearDown: function () { this.tearDownStubs(); },
"should fail when method fails": function () {
"fails when method does not exist": function () {
sinon.stub(this.stub, "calledWithNew");
assert.exception(function () {
sinon.assert.calledWithNew(null);
});
assert.isFalse(this.stub.calledWithNew.called);
assert(sinon.assert.fail.called);
},
"fails when method is not stub": function () {
sinon.stub(this.stub, "calledWithNew");
assert.exception(function () {
sinon.assert.calledWithNew(function () {});
});
assert.isFalse(this.stub.calledWithNew.called);
assert(sinon.assert.fail.called);
},
"fails when method fails": function () {
sinon.stub(this.stub, "calledWithNew").returns(false);
var stub = this.stub;
assert.exception(function () {
sinon.assert.calledWithNew(stub);
});
assert(sinon.assert.fail.called);
},
"passes when method doesn't fail": function () {
sinon.stub(this.stub, "calledWithNew").returns(true);
var stub = this.stub;
sinon.assert.calledWithNew(stub);
assert.isFalse(sinon.assert.fail.called);
},
"calls pass callback": function () {
var a = new this.stub();
sinon.assert.calledWithNew(this.stub);
assert(sinon.assert.pass.calledOnce);
assert(sinon.assert.pass.calledWith("calledWithNew"));
}
},
"alwaysCalledWithNew": {
setUp: function () { this.setUpStubs(); },
tearDown: function () { this.tearDownStubs(); },
"fails when method does not exist": function () {
sinon.stub(this.stub, "alwaysCalledWithNew");
assert.exception(function () {
sinon.assert.alwaysCalledWithNew(null);
});
assert.isFalse(this.stub.alwaysCalledWithNew.called);
assert(sinon.assert.fail.called);
},
"fails when method is not stub": function () {
sinon.stub(this.stub, "alwaysCalledWithNew");
assert.exception(function () {
sinon.assert.alwaysCalledWithNew(function () {});
});
assert.isFalse(this.stub.alwaysCalledWithNew.called);
assert(sinon.assert.fail.called);
},
"fails when method fails": function () {
sinon.stub(this.stub, "alwaysCalledWithNew").returns(false);
var stub = this.stub;
assert.exception(function () {
sinon.assert.alwaysCalledWithNew(stub);
});
assert(sinon.assert.fail.called);
},
"passes when method doesn't fail": function () {
sinon.stub(this.stub, "alwaysCalledWithNew").returns(true);
var stub = this.stub;
sinon.assert.alwaysCalledWithNew(stub);
assert.isFalse(sinon.assert.fail.called);
},
"calls pass callback": function () {
var a = new this.stub();
sinon.assert.alwaysCalledWithNew(this.stub);
assert(sinon.assert.pass.calledOnce);
assert(sinon.assert.pass.calledWith("alwaysCalledWithNew"));
}
},
"calledWith": {
setUp: function () { this.setUpStubs(); },
tearDown: function () { this.tearDownStubs(); },
"fails when method fails": function () {
var object = {};

@@ -531,3 +608,3 @@ sinon.stub(this.stub, "calledWith").returns(false);

assertException(function () {
assert.exception(function () {
sinon.assert.calledWith(stub, object, 1);

@@ -540,3 +617,3 @@ });

"should not fail when method doesn't fail": function () {
"passes when method doesn't fail": function () {
var object = {};

@@ -546,3 +623,3 @@ sinon.stub(this.stub, "calledWith").returns(true);

assertNoException(function () {
refute.exception(function () {
sinon.assert.calledWith(stub, object, 1);

@@ -552,6 +629,6 @@ });

assert(this.stub.calledWith.calledWith(object, 1));
assertFalse(sinon.assert.fail.called);
assert.isFalse(sinon.assert.fail.called);
},
"should call pass callback": function () {
"calls pass callback": function () {
this.stub("yeah");

@@ -563,9 +640,9 @@ sinon.assert.calledWith(this.stub, "yeah");

}
});
},
testCase("SinonAssertCalledWithExactlyTest", {
setUp: stubSetUp,
tearDown: stubTearDown,
"calledWithExactly": {
setUp: function () { this.setUpStubs(); },
tearDown: function () { this.tearDownStubs(); },
"should fail when method fails": function () {
"fails when method fails": function () {
var object = {};

@@ -575,3 +652,3 @@ sinon.stub(this.stub, "calledWithExactly").returns(false);

assertException(function () {
assert.exception(function () {
sinon.assert.calledWithExactly(stub, object, 1);

@@ -584,3 +661,3 @@ });

"should not fail when method doesn't fail": function () {
"passes when method doesn't fail": function () {
var object = {};

@@ -590,3 +667,3 @@ sinon.stub(this.stub, "calledWithExactly").returns(true);

assertNoException(function () {
refute.exception(function () {
sinon.assert.calledWithExactly(stub, object, 1);

@@ -596,6 +673,6 @@ });

assert(this.stub.calledWithExactly.calledWithExactly(object, 1));
assertFalse(sinon.assert.fail.called);
assert.isFalse(sinon.assert.fail.called);
},
"should call pass callback": function () {
"calls pass callback": function () {
this.stub("yeah");

@@ -607,9 +684,9 @@ sinon.assert.calledWithExactly(this.stub, "yeah");

}
});
},
testCase("SinonAssertNeverCalledWithTest", {
setUp: stubSetUp,
tearDown: stubTearDown,
"neverCalledWith": {
setUp: function () { this.setUpStubs(); },
tearDown: function () { this.tearDownStubs(); },
"should fail when method fails": function () {
"fails when method fails": function () {
var object = {};

@@ -619,3 +696,3 @@ sinon.stub(this.stub, "neverCalledWith").returns(false);

assertException(function () {
assert.exception(function () {
sinon.assert.neverCalledWith(stub, object, 1);

@@ -628,3 +705,3 @@ });

"should not fail when method doesn't fail": function () {
"passes when method doesn't fail": function () {
var object = {};

@@ -634,3 +711,3 @@ sinon.stub(this.stub, "neverCalledWith").returns(true);

assertNoException(function () {
refute.exception(function () {
sinon.assert.neverCalledWith(stub, object, 1);

@@ -640,6 +717,6 @@ });

assert(this.stub.neverCalledWith.calledWith(object, 1));
assertFalse(sinon.assert.fail.called);
assert.isFalse(sinon.assert.fail.called);
},
"should call pass callback": function () {
"calls pass callback": function () {
this.stub("yeah");

@@ -651,13 +728,13 @@ sinon.assert.neverCalledWith(this.stub, "nah!");

}
});
},
testCase("SinonAssertThrewTest", {
setUp: stubSetUp,
tearDown: stubTearDown,
"threwTest": {
setUp: function () { this.setUpStubs(); },
tearDown: function () { this.tearDownStubs(); },
"should fail when method fails": function () {
"fails when method fails": function () {
sinon.stub(this.stub, "threw").returns(false);
var stub = this.stub;
assertException(function () {
assert.exception(function () {
sinon.assert.threw(stub, 1, 2);

@@ -670,7 +747,7 @@ });

"should not fail when method doesn't fail": function () {
"passes when method doesn't fail": function () {
sinon.stub(this.stub, "threw").returns(true);
var stub = this.stub;
assertNoException(function () {
refute.exception(function () {
sinon.assert.threw(stub, 1, 2);

@@ -680,6 +757,6 @@ });

assert(this.stub.threw.calledWithExactly(1, 2));
assertFalse(sinon.assert.fail.called);
assert.isFalse(sinon.assert.fail.called);
},
"should call pass callback": function () {
"calls pass callback": function () {
sinon.stub(this.stub, "threw").returns(true);

@@ -692,9 +769,9 @@ this.stub();

}
});
},
testCase("SinonAssertCallCountTest", {
setUp: stubSetUp,
tearDown: stubTearDown,
"callCount": {
setUp: function () { this.setUpStubs(); },
tearDown: function () { this.tearDownStubs(); },
"should fail when method fails": function () {
"fails when method fails": function () {
this.stub();

@@ -704,3 +781,3 @@ this.stub();

assertException(function () {
assert.exception(function () {
sinon.assert.callCount(stub, 3);

@@ -712,14 +789,14 @@ });

"should not fail when method doesn't fail": function () {
"passes when method doesn't fail": function () {
var stub = this.stub;
this.stub.callCount = 3;
assertNoException(function () {
refute.exception(function () {
sinon.assert.callCount(stub, 3);
});
assertFalse(sinon.assert.fail.called);
assert.isFalse(sinon.assert.fail.called);
},
"should call pass callback": function () {
"calls pass callback": function () {
this.stub();

@@ -731,10 +808,10 @@ sinon.assert.callCount(this.stub, 1);

}
});
},
testCase("AssertAlwaysCalledOnTest", {
setUp: stubSetUp,
tearDown: stubTearDown,
"alwaysCalledOn": {
setUp: function () { this.setUpStubs(); },
tearDown: function () { this.tearDownStubs(); },
"should fail if method is missing": function () {
assertException(function () {
"fails if method is missing": function () {
assert.exception(function () {
sinon.assert.alwaysCalledOn();

@@ -744,4 +821,4 @@ });

"should fail if method is not fake": function () {
assertException(function () {
"fails if method is not fake": function () {
assert.exception(function () {
sinon.assert.alwaysCalledOn(function () {}, {});

@@ -751,7 +828,7 @@ });

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

@@ -763,3 +840,3 @@ });

"should not fail if stub returns true": function () {
"passes if stub returns true": function () {
var stub = sinon.stub.create();

@@ -770,6 +847,6 @@ sinon.stub(stub, "alwaysCalledOn").returns(true);

assertFalse(sinon.assert.fail.called);
assert.isFalse(sinon.assert.fail.called);
},
"should call pass callback": function () {
"calls pass callback": function () {
this.stub();

@@ -781,5 +858,5 @@ sinon.assert.alwaysCalledOn(this.stub, this);

}
});
},
testCase("AssertAlwaysCalledWithTest", {
"alwaysCalledWith": {
setUp: function () {

@@ -795,4 +872,4 @@ sinon.stub(sinon.assert, "fail").throws();

"should fail if method is missing": function () {
assertException(function () {
"fails if method is missing": function () {
assert.exception(function () {
sinon.assert.alwaysCalledWith();

@@ -802,4 +879,4 @@ });

"should fail if method is not fake": function () {
assertException(function () {
"fails if method is not fake": function () {
assert.exception(function () {
sinon.assert.alwaysCalledWith(function () {});

@@ -809,7 +886,7 @@ });

"should fail if stub returns false": function () {
"fails if stub returns false": function () {
var stub = sinon.stub.create();
sinon.stub(stub, "alwaysCalledWith").returns(false);
assertException(function () {
assert.exception(function () {
sinon.assert.alwaysCalledWith(stub, {}, []);

@@ -821,3 +898,3 @@ });

"should not fail if stub returns true": function () {
"passes if stub returns true": function () {
var stub = sinon.stub.create();

@@ -828,6 +905,6 @@ sinon.stub(stub, "alwaysCalledWith").returns(true);

assertFalse(sinon.assert.fail.called);
assert.isFalse(sinon.assert.fail.called);
},
"should call pass callback": function () {
"calls pass callback": function () {
var spy = sinon.spy();

@@ -840,5 +917,5 @@ spy("Hello");

}
});
},
testCase("AssertAlwaysCalledWithExactlyTest", {
"alwaysCalledWithExactly": {
setUp: function () {

@@ -854,3 +931,3 @@ sinon.stub(sinon.assert, "fail");

"should fail if stub returns false": function () {
"fails if stub returns false": function () {
var stub = sinon.stub.create();

@@ -864,3 +941,3 @@ sinon.stub(stub, "alwaysCalledWithExactly").returns(false);

"should not fail if stub returns true": function () {
"passes if stub returns true": function () {
var stub = sinon.stub.create();

@@ -871,6 +948,6 @@ sinon.stub(stub, "alwaysCalledWithExactly").returns(true);

assertFalse(sinon.assert.fail.called);
assert.isFalse(sinon.assert.fail.called);
},
"should call pass callback": function () {
"calls pass callback": function () {
var spy = sinon.spy();

@@ -883,35 +960,35 @@ spy("Hello");

}
});
},
testCase("SinonAssertExposeTest", {
"should expose asserts into object": function () {
"expose": {
"exposes asserts into object": function () {
var test = {};
sinon.assert.expose(test);
assertFunction(test.fail);
assertString(test.failException);
assertFunction(test.assertCalled);
assertFunction(test.assertCalledOn);
assertFunction(test.assertCalledWith);
assertFunction(test.assertCalledWithExactly);
assertFunction(test.assertThrew);
assertFunction(test.assertCallCount);
assert.isFunction(test.fail);
assert.isString(test.failException);
assert.isFunction(test.assertCalled);
assert.isFunction(test.assertCalledOn);
assert.isFunction(test.assertCalledWith);
assert.isFunction(test.assertCalledWithExactly);
assert.isFunction(test.assertThrew);
assert.isFunction(test.assertCallCount);
},
"should expose asserts into global": function () {
sinon.assert.expose(global, {
"exposes asserts into global": function () {
sinon.assert.expose(this.global, {
includeFail: false
});
assertEquals("undefined", typeof failException);
assertFunction(assertCalled);
assertFunction(assertCalledOn);
assertFunction(assertCalledWith);
assertFunction(assertCalledWithExactly);
assertFunction(assertThrew);
assertFunction(assertCallCount);
assert.equals(typeof failException, "undefined");
assert.isFunction(assertCalled);
assert.isFunction(assertCalledOn);
assert.isFunction(assertCalledWith);
assert.isFunction(assertCalledWithExactly);
assert.isFunction(assertThrew);
assert.isFunction(assertCallCount);
},
"should fail exposed asserts without errors": function () {
sinon.assert.expose(global, {
"fails exposed asserts without errors": function () {
sinon.assert.expose(this.global, {
includeFail: false

@@ -923,25 +1000,23 @@ });

} catch (e) {
assertEquals("expected spy to have been called at least once but was never called", e.message);
assert.equals(e.message, "expected spy to have been called at least once but was never called");
}
},
"should expose asserts into object without prefixes": function () {
"exposes asserts into object without prefixes": function () {
var test = {};
sinon.assert.expose(test, {
prefix: ""
});
sinon.assert.expose(test, { prefix: "" });
assertFunction(test.fail);
assertString(test.failException);
assertFunction(test.called);
assertFunction(test.calledOn);
assertFunction(test.calledWith);
assertFunction(test.calledWithExactly);
assertFunction(test.threw);
assertFunction(test.callCount);
assert.isFunction(test.fail);
assert.isString(test.failException);
assert.isFunction(test.called);
assert.isFunction(test.calledOn);
assert.isFunction(test.calledWith);
assert.isFunction(test.calledWithExactly);
assert.isFunction(test.threw);
assert.isFunction(test.callCount);
},
"should throw if target is undefined": function () {
assertException(function () {
"throws if target is undefined": function () {
assert.exception(function () {
sinon.assert.expose();

@@ -951,10 +1026,10 @@ }, "TypeError");

"should throw if target is null": function () {
assertException(function () {
"throws if target is null": function () {
assert.exception(function () {
sinon.assert.expose(null);
}, "TypeError");
}
});
},
testCase("AssertionMessageTest", {
"message": {
setUp: function () {

@@ -977,5 +1052,5 @@ this.obj = {

"assert.called exception message": function () {
assertEquals("expected doSomething to have been called at " +
"least once but was never called",
this.message("called", this.obj.doSomething));
assert.equals(this.message("called", this.obj.doSomething),
"expected doSomething to have been called at " +
"least once but was never called");
},

@@ -986,5 +1061,5 @@

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

@@ -998,6 +1073,6 @@

assertEquals("expected doSomething to not have been called " +
"but was called 4 times\n doSomething()\n " +
"doSomething()\n doSomething()\n doSomething()",
this.message("notCalled", this.obj.doSomething));
assert.equals(this.message("notCalled", this.obj.doSomething),
"expected doSomething to not have been called " +
"but was called 4 times\n doSomething()\n " +
"doSomething()\n doSomething()\n doSomething()");
},

@@ -1011,6 +1086,6 @@

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.equals(this.message("notCalled", this.obj.doSomething),
"expected doSomething to not have been called " +
"but was called 4 times\n doSomething()\n " +
"doSomething(3)\n doSomething(42, 1)\n doSomething()");
},

@@ -1027,5 +1102,7 @@

assertEquals("expected doSomething, doop, foo to be called in " +
"order but were called as doop, doSomething, foo",
this.message("callOrder", this.obj.doSomething, obj.doop, obj.foo));
var message = this.message("callOrder", this.obj.doSomething, obj.doop, obj.foo);
assert.equals(message,
"expected doSomething, doop, foo to be called in " +
"order but were called as doop, doSomething, foo");
},

@@ -1036,5 +1113,5 @@

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

@@ -1046,11 +1123,11 @@

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

@@ -1061,5 +1138,5 @@

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

@@ -1073,4 +1150,4 @@

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));
assert.equals(this.message("calledThrice", this.obj.doSomething),
"expected doSomething to be called thrice but was called 4 times\n doSomething()\n doSomething()\n doSomething()\n doSomething()");
},

@@ -1089,4 +1166,4 @@

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.equals(this.message("calledOn", this.obj.doSomething, this.obj),
"expected doSomething to be called with [Oh yeah] as this but was called with [Oh no], [Oh well]");
},

@@ -1106,14 +1183,141 @@

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));
assert.equals(this.message("alwaysCalledOn", this.obj.doSomething, this.obj),
"expected doSomething to always be called with [Oh yeah] as this but was called with [Oh no], [Oh well], [Oh yeah]");
},
"assert.calledWithNew exception message": function () {
this.obj.doSomething();
assert.equals(this.message("calledWithNew", this.obj.doSomething),
"expected doSomething to be called with new");
},
"assert.alwaysCalledWithNew exception message": function () {
var a = new this.obj.doSomething();
this.obj.doSomething();
assert.equals(this.message("alwaysCalledWithNew", this.obj.doSomething),
"expected doSomething to always be called with new");
},
"assert.calledWith exception message": function () {
this.obj.doSomething(1, 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"));
assert.equals(this.message("calledWith", this.obj.doSomething, 4, 3, "hey"),
"expected doSomething to be called with arguments 4, 3, " +
"hey\n doSomething(1, 3, hey)");
},
"assert.calledWith match.any exception message": function () {
this.obj.doSomething(true, true);
assert.equals(this.message("calledWith", this.obj.doSomething, sinon.match.any, false),
"expected doSomething to be called with arguments " +
"any, false\n doSomething(true, true)");
},
"assert.calledWith match.defined exception message": function () {
this.obj.doSomething();
assert.equals(this.message("calledWith", this.obj.doSomething, sinon.match.defined),
"expected doSomething to be called with arguments " +
"defined\n doSomething()");
},
"assert.calledWith match.truthy exception message": function () {
this.obj.doSomething();
assert.equals(this.message("calledWith", this.obj.doSomething, sinon.match.truthy),
"expected doSomething to be called with arguments " +
"truthy\n doSomething()");
},
"assert.calledWith match.falsy exception message": function () {
this.obj.doSomething(true);
assert.equals(this.message("calledWith", this.obj.doSomething, sinon.match.falsy),
"expected doSomething to be called with arguments " +
"falsy\n doSomething(true)");
},
"assert.calledWith match.same exception message": function () {
this.obj.doSomething();
assert.equals(this.message("calledWith", this.obj.doSomething, sinon.match.same(1)),
"expected doSomething to be called with arguments " +
"same(1)\n doSomething()");
},
"assert.calledWith match.typeOf exception message": function () {
this.obj.doSomething();
assert.equals(this.message("calledWith", this.obj.doSomething, sinon.match.typeOf("string")),
"expected doSomething to be called with arguments " +
"typeOf(\"string\")\n doSomething()");
},
"assert.calledWith match.instanceOf exception message": function () {
this.obj.doSomething();
assert.equals(this.message("calledWith", this.obj.doSomething, sinon.match.instanceOf(function CustomType() {})),
"expected doSomething to be called with arguments " +
"instanceOf(CustomType)\n doSomething()");
},
"assert.calledWith match object exception message": function () {
this.obj.doSomething();
assert.equals(this.message("calledWith", this.obj.doSomething, sinon.match({ some: "value", and: 123 })),
"expected doSomething to be called with arguments " +
"match(some: value, and: 123)\n doSomething()");
},
"assert.calledWith match boolean exception message": function () {
this.obj.doSomething();
assert.equals(this.message("calledWith", this.obj.doSomething, sinon.match(true)),
"expected doSomething to be called with arguments " +
"match(true)\n doSomething()");
},
"assert.calledWith match number exception message": function () {
this.obj.doSomething();
assert.equals(this.message("calledWith", this.obj.doSomething, sinon.match(123)),
"expected doSomething to be called with arguments " +
"match(123)\n doSomething()");
},
"assert.calledWith match string exception message": function () {
this.obj.doSomething();
assert.equals(this.message("calledWith", this.obj.doSomething, sinon.match("Sinon")),
"expected doSomething to be called with arguments " +
"match(\"Sinon\")\n doSomething()");
},
"assert.calledWith match regexp exception message": function () {
this.obj.doSomething();
assert.equals(this.message("calledWith", this.obj.doSomething, sinon.match(/[a-z]+/)),
"expected doSomething to be called with arguments " +
"match(/[a-z]+/)\n doSomething()");
},
"assert.calledWith match test function exception message": function () {
this.obj.doSomething();
assert.equals(this.message("calledWith", this.obj.doSomething, sinon.match({ test: function custom() {} })),
"expected doSomething to be called with arguments " +
"match(custom)\n doSomething()");
},
"assert.calledWithMatch exception message": function () {
this.obj.doSomething(1, 3, "hey");
assert.equals(this.message("calledWithMatch", this.obj.doSomething, 4, 3, "hey"),
"expected doSomething to be called with match 4, 3, " +
"hey\n doSomething(1, 3, hey)");
},
"assert.alwaysCalledWith exception message": function () {

@@ -1123,13 +1327,22 @@ this.obj.doSomething(1, 3, "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"));
assert.equals(this.message("alwaysCalledWith", this.obj.doSomething, 1, "hey"),
"expected doSomething to always be called with arguments 1" +
", hey\n doSomething(1, 3, hey)\n doSomething(1, hey)");
},
"assert.alwaysCalledWithMatch exception message": function () {
this.obj.doSomething(1, 3, "hey");
this.obj.doSomething(1, "hey");
assert.equals(this.message("alwaysCalledWithMatch", this.obj.doSomething, 1, "hey"),
"expected doSomething to always be called with match 1" +
", hey\n doSomething(1, 3, hey)\n doSomething(1, hey)");
},
"assert.calledWithExactly exception message": function () {
this.obj.doSomething(1, 3, "hey");
assertEquals("expected doSomething to be called with exact arguments 1" +
", 3\n doSomething(1, 3, hey)",
this.message("calledWithExactly", this.obj.doSomething, 1, 3));
assert.equals(this.message("calledWithExactly", this.obj.doSomething, 1, 3),
"expected doSomething to be called with exact arguments 1" +
", 3\n doSomething(1, 3, hey)");
},

@@ -1141,7 +1354,6 @@

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

@@ -1152,8 +1364,15 @@

assertEquals("expected doSomething to never be called with " +
"arguments 1, 2\n doSomething(1, 2, 3)",
this.message("neverCalledWith",
this.obj.doSomething, 1, 2));
assert.equals(this.message("neverCalledWith", this.obj.doSomething, 1, 2),
"expected doSomething to never be called with " +
"arguments 1, 2\n doSomething(1, 2, 3)");
},
"assert.neverCalledWithMatch exception message": function () {
this.obj.doSomething(1, 2, 3);
assert.equals(this.message("neverCalledWithMatch", this.obj.doSomething, 1, 2),
"expected doSomething to never be called with match " +
"1, 2\n doSomething(1, 2, 3)");
},
"assert.threw exception message": function () {

@@ -1163,5 +1382,5 @@ this.obj.doSomething(1, 3, "hey");

assertEquals("doSomething did not throw exception\n" +
" doSomething(1, 3, hey)\n doSomething(1, 3)",
this.message("threw", this.obj.doSomething));
assert.equals(this.message("threw", this.obj.doSomething),
"doSomething did not throw exception\n" +
" doSomething(1, 3, hey)\n doSomething(1, 3)");
},

@@ -1173,7 +1392,7 @@

assertEquals("doSomething did not always throw exception\n" +
" doSomething(1, 3, hey)\n doSomething(1, 3)",
this.message("alwaysThrew", this.obj.doSomething));
assert.equals(this.message("alwaysThrew", this.obj.doSomething),
"doSomething did not always throw exception\n" +
" doSomething(1, 3, hey)\n doSomething(1, 3)");
}
});
}(typeof global == "object" ? global : this));
}
});
/*jslint onevar: false, eqeqeq: false, plusplus: false*/
/*globals testCase
sinon
fail
assert
assertArray
assertEquals
assertSame
assertNotSame
assertFunction
assertObject
assertException
assertNoException*/
/*globals sinon buster*/
/**

@@ -18,25 +7,23 @@ * @author Christian Johansen (christian@cjohansen.no)

*
* Copyright (c) 2010-2011 Christian Johansen
* Copyright (c) 2010-2012 Christian Johansen
*/
"use strict";
if (typeof require == "function" && typeof testCase == "undefined") {
var testCase = require("../test_case_shim");
if (typeof require == "function" && typeof module == "object") {
var buster = require("../runner");
var sinon = require("../../lib/sinon");
}
(function () {
testCase("CollectionCreateTest", {
"should create fake collection": function () {
var collection = sinon.create(sinon.collection);
buster.testCase("sinon.collection", {
"creates fake collection": function () {
var collection = sinon.create(sinon.collection);
assertFunction(collection.verify);
assertFunction(collection.restore);
assertFunction(collection.verifyAndRestore);
assertFunction(collection.stub);
assertFunction(collection.mock);
}
});
assert.isFunction(collection.verify);
assert.isFunction(collection.restore);
assert.isFunction(collection.verifyAndRestore);
assert.isFunction(collection.stub);
assert.isFunction(collection.mock);
},
testCase("CollectionStubTest", {
"stub": {
setUp: function () {

@@ -51,3 +38,3 @@ this.stub = sinon.stub;

"should call stub": function () {
"calls stub": function () {
var object = { method: function () {} };

@@ -62,6 +49,6 @@ var args;

assertEquals([object, "method"], args);
assert.equals(args, [object, "method"]);
},
"should add stub to fake array": function () {
"adds stub to fake array": function () {
var object = { method: function () {} };

@@ -75,6 +62,6 @@

assertEquals([object], this.collection.fakes);
assert.equals(this.collection.fakes, [object]);
},
"should append stubs to fake array": function () {
"appends stubs to fake array": function () {
var objects = [{ id: 42 }, { id: 17 }];

@@ -90,7 +77,40 @@ var i = 0;

assertEquals(objects, this.collection.fakes);
assert.equals(this.collection.fakes, objects);
},
"adds all object methods to fake array": function() {
var object = { method: function () {}, method2: function() {} };
sinon.stub = function() {
return object;
};
this.collection.stub(object);
assert.equals(this.collection.fakes, [object.method, object.method2]);
assert.equals(this.collection.fakes.length, 2);
},
"returns a stubbed object": function() {
var object = { method: function () {} };
sinon.stub = function () {
return object;
};
assert.equals(this.collection.stub(object), object);
},
"returns a stubbed method": function() {
var object = { method: function () {} };
sinon.stub = function () {
return object.method;
};
assert.equals(this.collection.stub(object, "method"), object.method);
}
});
},
testCase("CollectionStubAnythingTest", {
"stubAnything": {
setUp: function () {

@@ -101,26 +121,26 @@ this.object = { property: 42 };

"should stub number property": function () {
"stubs number property": function () {
this.collection.stub(this.object, "property", 1);
assertEquals(1, this.object.property);
assert.equals(this.object.property, 1);
},
"should restore number property": function () {
"restores number property": function () {
this.collection.stub(this.object, "property", 1);
this.collection.restore();
assertEquals(42, this.object.property);
assert.equals(this.object.property, 42);
},
"should fail if property does not exist": function () {
"fails if property does not exist": function () {
var collection = this.collection;
var object = {};
assertException(function () {
assert.exception(function () {
collection.stub(object, "prop", 1);
});
}
});
},
testCase("CollectionMockTest", {
"mock": {
setUp: function () {

@@ -135,3 +155,3 @@ this.mock = sinon.mock;

"should call mock": function () {
"calls mock": function () {
var object = { id: 42 };

@@ -146,6 +166,6 @@ var args;

assertEquals([object, "method"], args);
assert.equals(args, [object, "method"]);
},
"should add mock to fake array": function () {
"adds mock to fake array": function () {
var object = { id: 42 };

@@ -159,6 +179,6 @@

assertEquals([object], this.collection.fakes);
assert.equals(this.collection.fakes, [object]);
},
"should append mocks to fake array": function () {
"appends mocks to fake array": function () {
var objects = [{ id: 42 }, { id: 17 }];

@@ -174,7 +194,7 @@ var i = 0;

assertEquals(objects, this.collection.fakes);
assert.equals(this.collection.fakes, objects);
}
});
},
testCase("CollectionStubAndMockTest", {
"stubAndMockTest": {
setUp: function () {

@@ -191,3 +211,3 @@ this.mock = sinon.mock;

"should append mocks and stubs to fake array": function () {
"appends mocks and stubs to fake array": function () {
var objects = [{ id: 42 }, { id: 17 }];

@@ -203,7 +223,7 @@ var i = 0;

assertEquals(objects, this.collection.fakes);
assert.equals(this.collection.fakes, objects);
}
});
},
testCase("CollectionVerifyTest", {
"verify": {
setUp: function () {

@@ -213,3 +233,3 @@ this.collection = sinon.create(sinon.collection);

"should call verify on all fakes": function () {
"calls verify on all fakes": function () {
this.collection.fakes = [{

@@ -226,5 +246,5 @@ verify: sinon.spy.create()

}
});
},
testCase("CollectionRestoreTest", {
"restore": {
setUp: function () {

@@ -239,3 +259,3 @@ this.collection = sinon.create(sinon.collection);

"should call restore on all fakes": function () {
"calls restore on all fakes": function () {
var fake0 = this.collection.fakes[0];

@@ -250,9 +270,21 @@ var fake1 = this.collection.fakes[1];

"should remove from collection when restored": function () {
this.collection.restore();
assert(this.collection.fakes.length == 0);
"removes from collection when restored": function () {
this.collection.restore();
assert(this.collection.fakes.length == 0);
},
"restores functions when stubbing entire object": function () {
var a = function () {};
var b = function () {};
var obj = { a: a, b: b };
this.collection.stub(obj);
this.collection.restore();
assert.same(obj.a, a);
assert.same(obj.b, b);
}
});
},
testCase("CollectionVerifyAndRestoreTest", {
"verifyAndRestore": {
setUp: function () {

@@ -262,3 +294,3 @@ this.collection = sinon.create(sinon.collection);

"should call verify and restore": function () {
"calls verify and restore": function () {
this.collection.verify = sinon.spy.create();

@@ -273,7 +305,7 @@ this.collection.restore = sinon.spy.create();

"should throw when restore throws": function () {
"throws when restore throws": function () {
this.collection.verify = sinon.spy.create();
this.collection.restore = sinon.stub.create().throws();
assertException(function () {
assert.exception(function () {
this.collection.verifyAndRestore();

@@ -283,3 +315,3 @@ });

"should call restore when restore throws": function () {
"calls restore when restore throws": function () {
this.collection.verify = sinon.spy.create();

@@ -294,5 +326,5 @@ this.collection.restore = sinon.stub.create().throws();

}
});
},
testCase("CollectionInjectTest", {
"injectTest": {
setUp: function () {

@@ -302,18 +334,18 @@ this.collection = sinon.create(sinon.collection);

"should inject fakes into object": function () {
"injects fakes into object": function () {
var obj = {};
this.collection.inject(obj);
assertFunction(obj.spy);
assertFunction(obj.stub);
assertFunction(obj.mock);
assert.isFunction(obj.spy);
assert.isFunction(obj.stub);
assert.isFunction(obj.mock);
},
"should return argument": function () {
"returns argument": function () {
var obj = {};
assertSame(obj, this.collection.inject(obj));
assert.same(this.collection.inject(obj), obj);
},
"should inject spy, stub, mock bound to collection": sinon.test(function () {
"injects spy, stub, mock bound to collection": sinon.test(function () {
var obj = {};

@@ -341,3 +373,3 @@ this.collection.inject(obj);

})
});
}());
}
});
/*jslint onevar: false*/
/*globals testCase
sinon
fail
assert
assertFalse
assertFunction
assertObject
assertSame
assertNotSame
assertEquals
assertNoException
assertException*/
/*globals sinon buster*/
/**

@@ -18,37 +7,27 @@ * @author Christian Johansen (christian@cjohansen.no)

*
* Copyright (c) 2010-2011 Christian Johansen
* Copyright (c) 2010-2012 Christian Johansen
*/
"use strict";
if (typeof require == "function" && typeof testCase == "undefined") {
var testCase = require("../test_case_shim");
if (typeof require == "function" && typeof module == "object") {
var buster = require("../runner");
var sinon = require("../../lib/sinon");
}
(function () {
testCase("MockCreateTest", {
"should be function": function () {
assertFunction(sinon.mock.create);
},
"should return object": function () {
buster.testCase("sinon.mock", {
"create": {
"returns function with expects method": function () {
var mock = sinon.mock.create({});
assertObject(mock);
assert.isFunction(mock.expects);
},
"should return function with expects method": function () {
var mock = sinon.mock.create({});
assertFunction(mock.expects);
},
"should throw without object": function () {
assertException(function () {
"throws without object": function () {
assert.exception(function () {
sinon.mock.create();
}, "TypeError");
}
});
},
testCase("MockExpectsTest", {
"expects": {
setUp: function () {

@@ -58,6 +37,6 @@ this.mock = sinon.mock.create({ someMethod: function () {} });

"should throw without method": function () {
"throws without method": function () {
var mock = this.mock;
assertException(function () {
assert.exception(function () {
mock.expects();

@@ -67,557 +46,564 @@ }, "TypeError");

"should return expectation": function () {
"returns expectation": function () {
var result = this.mock.expects("someMethod");
assertFunction(result);
assertEquals("someMethod", result.method);
assert.isFunction(result);
assert.equals(result.method, "someMethod");
},
"should throw if expecting a non-existent method": function () {
"throws if expecting a non-existent method": function () {
var mock = this.mock;
assertException(function () {
assert.exception(function () {
mock.expects("someMethod2");
});
}
});
},
testCase("ExpectationTest", {
"expectation": {
setUp: function () {
this.method = "myMeth";
this.expectation = sinon.expectation.create(this.methodName);
this.expectation = sinon.expectation.create(this.method);
},
call: function () {
"call expectation": function () {
this.expectation();
assertFunction(this.expectation.invoke);
assert.isFunction(this.expectation.invoke);
assert(this.expectation.called);
},
"should be invokable": function () {
"is invokable": function () {
var expectation = this.expectation;
assertNoException(function () {
refute.exception(function () {
expectation();
});
}
});
},
function expectationSetUp() {
this.method = "myMeth";
this.expectation = sinon.expectation.create(this.method);
}
"returns": {
"returns configured return value": function () {
var object = {};
this.expectation.returns(object);
function mockSetUp() {
this.method = function () {};
this.object = { method: this.method };
this.mock = sinon.mock.create(this.object);
}
assert.same(this.expectation(), object);
}
},
testCase("ExpectationReturnsTest", {
setUp: expectationSetUp,
"call": {
"is called with correct this value": function () {
var object = { method: this.expectation };
object.method();
"should return configured return value": function () {
var object = {};
this.expectation.returns(object);
assert(this.expectation.calledOn(object));
}
},
assertSame(object, this.expectation());
}
});
"callCount": {
"onlys be invokable once by default": function () {
var expectation = this.expectation;
expectation();
testCase("ExpectationCallTest", {
setUp: expectationSetUp,
assert.exception(function () {
expectation();
}, "ExpectationError");
},
"should be called with correct this value": function () {
var object = { method: this.expectation };
object.method();
"throw readable error": function () {
var expectation = this.expectation;
expectation();
assert(this.expectation.calledOn(object));
}
});
try {
expectation();
buster.assertions.fail("Expected to throw");
} catch (e) {
assert.equals(e.message, "myMeth already called once");
}
}
},
testCase("ExpectationCallCountTest", {
setUp: expectationSetUp,
"callCountNever": {
"is not callable": function () {
var expectation = this.expectation;
expectation.never();
"should only be invokable once by default": function () {
var expectation = this.expectation;
expectation();
assert.exception(function () {
expectation();
}, "ExpectationError");
},
assertException(function () {
expectation();
}, "ExpectationError");
"returns expectation for chaining": function () {
assert.same(this.expectation.never(), this.expectation);
}
},
"throw readable error": function () {
var expectation = this.expectation;
expectation();
"callCountOnce": {
"allows one call": function () {
var expectation = this.expectation;
expectation.once();
expectation();
try {
expectation();
fail("Expected to throw");
} catch (e) {
assertEquals("myMeth already called once", e.message);
assert.exception(function () {
expectation();
}, "ExpectationError");
},
"returns expectation for chaining": function () {
assert.same(this.expectation.once(), this.expectation);
}
}
});
},
testCase("ExpectationCallCountNeverTest", {
setUp: expectationSetUp,
"callCountTwice": {
"allows two calls": function () {
var expectation = this.expectation;
expectation.twice();
expectation();
expectation();
"should not be callable": function () {
var expectation = this.expectation;
expectation.never();
assert.exception(function () {
expectation();
}, "ExpectationError");
},
assertException(function () {
expectation();
}, "ExpectationError");
"returns expectation for chaining": function () {
assert.same(this.expectation.twice(), this.expectation);
}
},
"should return expectation for chaining": function () {
assertSame(this.expectation, this.expectation.never());
}
});
"callCountThrice": {
"allows three calls": function () {
var expectation = this.expectation;
expectation.thrice();
expectation();
expectation();
expectation();
testCase("ExpectationCallCountOnceTest", {
setUp: expectationSetUp,
assert.exception(function () {
expectation();
}, "ExpectationError");
},
"should allow one call": function () {
var expectation = this.expectation;
expectation.once();
expectation();
"returns expectation for chaining": function () {
assert.same(this.expectation.thrice(), this.expectation);
}
},
assertException(function () {
"callCountExactly": {
"allows specified number of calls": function () {
var expectation = this.expectation;
expectation.exactly(2);
expectation();
}, "ExpectationError");
},
expectation();
"should return expectation for chaining": function () {
assertSame(this.expectation, this.expectation.once());
}
});
assert.exception(function () {
expectation();
}, "ExpectationError");
},
testCase("ExpectationCallCountTwiceTest", {
setUp: expectationSetUp,
"returns expectation for chaining": function () {
assert.same(this.expectation.exactly(2), this.expectation);
},
"should allow two calls": function () {
var expectation = this.expectation;
expectation.twice();
expectation();
expectation();
"throws without argument": function () {
var expectation = this.expectation;
assertException(function () {
expectation();
}, "ExpectationError");
},
assert.exception(function () {
expectation.exactly();
}, "TypeError");
},
"should return expectation for chaining": function () {
assertSame(this.expectation, this.expectation.twice());
}
});
"throws without number": function () {
var expectation = this.expectation;
testCase("ExpectationCallCountThriceTest", {
setUp: expectationSetUp,
assert.exception(function () {
expectation.exactly("12");
}, "TypeError");
}
},
"should allow three calls": function () {
var expectation = this.expectation;
expectation.thrice();
expectation();
expectation();
expectation();
"atLeast": {
"throws without argument": function () {
var expectation = this.expectation;
assertException(function () {
expectation();
}, "ExpectationError");
},
assert.exception(function () {
expectation.atLeast();
}, "TypeError");
},
"should return expectation for chaining": function () {
assertSame(this.expectation, this.expectation.thrice());
}
});
"throws without number": function () {
var expectation = this.expectation;
testCase("ExpectationCallCountExactlyTest", {
setUp: expectationSetUp,
assert.exception(function () {
expectation.atLeast({});
}, "TypeError");
},
"should allow specified number of calls": function () {
var expectation = this.expectation;
expectation.exactly(2);
expectation();
expectation();
"returns expectation for chaining": function () {
assert.same(this.expectation.atLeast(2), this.expectation);
},
assertException(function () {
"allows any number of calls": function () {
var expectation = this.expectation;
expectation.atLeast(2);
expectation();
}, "ExpectationError");
},
expectation();
"should return expectation for chaining": function () {
assertSame(this.expectation, this.expectation.exactly(2));
},
refute.exception(function () {
expectation();
expectation();
});
},
"should throw without argument": function () {
var expectation = this.expectation;
"nots be met with too few calls": function () {
this.expectation.atLeast(2);
this.expectation();
assertException(function () {
expectation.exactly();
}, "TypeError");
},
assert.isFalse(this.expectation.met());
},
"should throw without number": function () {
var expectation = this.expectation;
"is met with exact calls": function () {
this.expectation.atLeast(2);
this.expectation();
this.expectation();
assertException(function () {
expectation.exactly("12");
}, "TypeError");
}
});
assert(this.expectation.met());
},
testCase("MockExpectationAtLeastTest", {
setUp: expectationSetUp,
"is met with excessive calls": function () {
this.expectation.atLeast(2);
this.expectation();
this.expectation();
this.expectation();
"should throw without argument": function () {
var expectation = this.expectation;
assert(this.expectation.met());
},
assertException(function () {
expectation.atLeast();
}, "TypeError");
},
"nots throw when exceeding at least expectation": function () {
var obj = { foobar: function () {} };
var mock = sinon.mock(obj);
mock.expects("foobar").atLeast(1);
"should throw without number": function () {
var expectation = this.expectation;
obj.foobar();
assertException(function () {
expectation.atLeast({});
}, "TypeError");
refute.exception(function () {
obj.foobar();
mock.verify();
});
}
},
"should return expectation for chaining": function () {
assertSame(this.expectation, this.expectation.atLeast(2));
},
"atMost": {
"throws without argument": function () {
var expectation = this.expectation;
"should allow any number of calls": function () {
var expectation = this.expectation;
expectation.atLeast(2);
expectation();
expectation();
assert.exception(function () {
expectation.atMost();
}, "TypeError");
},
assertNoException(function () {
expectation();
expectation();
});
},
"throws without number": function () {
var expectation = this.expectation;
"should not be met with too few calls": function () {
this.expectation.atLeast(2);
this.expectation();
assert.exception(function () {
expectation.atMost({});
}, "TypeError");
},
assertFalse(this.expectation.met());
},
"returns expectation for chaining": function () {
assert.same(this.expectation.atMost(2), this.expectation);
},
"should be met with exact calls": function () {
this.expectation.atLeast(2);
this.expectation();
this.expectation();
"allows fewer calls": function () {
var expectation = this.expectation;
expectation.atMost(2);
assert(this.expectation.met());
},
refute.exception(function () {
expectation();
});
},
"should be met with excessive calls": function () {
this.expectation.atLeast(2);
this.expectation();
this.expectation();
this.expectation();
"is met with fewer calls": function () {
this.expectation.atMost(2);
this.expectation();
assert(this.expectation.met());
}
});
assert(this.expectation.met());
},
testCase("MockExpectationAtMostTest", {
setUp: expectationSetUp,
"is met with exact calls": function () {
this.expectation.atMost(2);
this.expectation();
this.expectation();
"should throw without argument": function () {
var expectation = this.expectation;
assert(this.expectation.met());
},
assertException(function () {
expectation.atMost();
}, "TypeError");
},
"nots be met with excessive calls": function () {
var expectation = this.expectation;
this.expectation.atMost(2);
this.expectation();
this.expectation();
"should throw without number": function () {
var expectation = this.expectation;
assert.exception(function () {
expectation();
}, "ExpectationError");
assertException(function () {
expectation.atMost({});
}, "TypeError");
assert.isFalse(this.expectation.met());
}
},
"should return expectation for chaining": function () {
assertSame(this.expectation, this.expectation.atMost(2));
},
"atMostAndAtLeast": {
setUp: function () {
this.expectation.atLeast(2);
this.expectation.atMost(3);
},
"should allow fewer calls": function () {
var expectation = this.expectation;
expectation.atMost(2);
"nots be met with too few calls": function () {
this.expectation();
assertNoException(function () {
expectation();
});
},
assert.isFalse(this.expectation.met());
},
"should be met with fewer calls": function () {
this.expectation.atMost(2);
this.expectation();
"is met with minimum calls": function () {
this.expectation();
this.expectation();
assert(this.expectation.met());
},
assert(this.expectation.met());
},
"should be met with exact calls": function () {
this.expectation.atMost(2);
this.expectation();
this.expectation();
"is met with maximum calls": function () {
this.expectation();
this.expectation();
this.expectation();
assert(this.expectation.met());
},
assert(this.expectation.met());
},
"should not be met with excessive calls": function () {
var expectation = this.expectation;
this.expectation.atMost(2);
this.expectation();
this.expectation();
assertException(function () {
"throws with excessive calls": function () {
var expectation = this.expectation;
expectation();
}, "ExpectationError");
expectation();
expectation();
assertFalse(this.expectation.met());
}
});
testCase("MockExpectationAtMostAndAtLeastTest", {
setUp: function () {
expectationSetUp.call(this);
this.expectation.atLeast(2);
this.expectation.atMost(3);
assert.exception(function () {
expectation();
}, "ExpectationError");
}
},
"should not be met with too few calls": function () {
this.expectation();
"met": {
"nots be met when not called enough times": function () {
assert.isFalse(this.expectation.met());
},
assertFalse(this.expectation.met());
},
"is met when called enough times": function () {
this.expectation();
"should be met with minimum calls": function () {
this.expectation();
this.expectation();
assert(this.expectation.met());
},
assert(this.expectation.met());
},
"nots be met when called too many times": function () {
this.expectation();
"should be met with maximum calls": function () {
this.expectation();
this.expectation();
this.expectation();
try {
this.expectation();
} catch (e) {}
assert(this.expectation.met());
assert.isFalse(this.expectation.met());
}
},
"should throw with excessive calls": function () {
var expectation = this.expectation;
expectation();
expectation();
expectation();
"withArgs": {
"returns expectation for chaining": function () {
assert.same(this.expectation.withArgs(1), this.expectation);
},
assertException(function () {
expectation();
}, "ExpectationError");
}
});
"accepts call with expected args": function () {
this.expectation.withArgs(1, 2, 3);
this.expectation(1, 2, 3);
testCase("MockExpectationMetTest", {
setUp: expectationSetUp,
assert(this.expectation.met());
},
"should not be met when not called enough times": function () {
assertFalse(this.expectation.met());
},
"throws when called without args": function () {
var expectation = this.expectation;
expectation.withArgs(1, 2, 3);
"should be met when called enough times": function () {
this.expectation();
assert.exception(function () {
expectation();
}, "ExpectationError");
},
assert(this.expectation.met());
},
"throws when called with too few args": function () {
var expectation = this.expectation;
expectation.withArgs(1, 2, 3);
"should not be met when called too many times": function () {
this.expectation();
assert.exception(function () {
expectation(1, 2);
}, "ExpectationError");
},
try {
this.expectation();
} catch (e) {}
"throws when called with wrong args": function () {
var expectation = this.expectation;
expectation.withArgs(1, 2, 3);
assertFalse(this.expectation.met());
}
});
assert.exception(function () {
expectation(2, 2, 3);
}, "ExpectationError");
},
testCase("MockExpectationWithArgsTest", {
setUp: expectationSetUp,
"allows excessive args": function () {
var expectation = this.expectation;
expectation.withArgs(1, 2, 3);
"should be method": function () {
assertFunction(this.expectation.withArgs);
},
refute.exception(function () {
expectation(1, 2, 3, 4);
});
},
"should return expectation for chaining": function () {
assertSame(this.expectation, this.expectation.withArgs(1));
},
"calls accept with no args": function () {
this.expectation.withArgs();
this.expectation();
"should accept call with expected args": function () {
this.expectation.withArgs(1, 2, 3);
this.expectation(1, 2, 3);
assert(this.expectation.met());
},
assert(this.expectation.met());
},
"allows no args called with excessive args": function () {
var expectation = this.expectation;
expectation.withArgs();
"should throw when called without args": function () {
var expectation = this.expectation;
expectation.withArgs(1, 2, 3);
assertException(function () {
expectation();
}, "ExpectationError");
refute.exception(function () {
expectation(1, 2, 3);
});
}
},
"should throw when called with too few args": function () {
var expectation = this.expectation;
expectation.withArgs(1, 2, 3);
"withExactArgs": {
"returns expectation for chaining": function () {
assert.same(this.expectation.withExactArgs(1), this.expectation);
},
assertException(function () {
expectation(1, 2);
}, "ExpectationError");
},
"accepts call with expected args": function () {
this.expectation.withExactArgs(1, 2, 3);
this.expectation(1, 2, 3);
"should throw when called with wrong args": function () {
var expectation = this.expectation;
expectation.withArgs(1, 2, 3);
assert(this.expectation.met());
},
assertException(function () {
expectation(2, 2, 3);
}, "ExpectationError");
},
"throws when called without args": function () {
var expectation = this.expectation;
expectation.withExactArgs(1, 2, 3);
"should allow excessive args": function () {
var expectation = this.expectation;
expectation.withArgs(1, 2, 3);
assert.exception(function () {
expectation();
}, "ExpectationError");
},
assertNoException(function () {
expectation(1, 2, 3, 4);
});
}
});
"throws when called with too few args": function () {
var expectation = this.expectation;
expectation.withExactArgs(1, 2, 3);
testCase("MockExpectationWithExactArgsTest", {
setUp: expectationSetUp,
assert.exception(function () {
expectation(1, 2);
}, "ExpectationError");
},
"should be method": function () {
assertFunction(this.expectation.withExactArgs);
},
"throws when called with wrong args": function () {
var expectation = this.expectation;
expectation.withExactArgs(1, 2, 3);
"should return expectation for chaining": function () {
assertSame(this.expectation, this.expectation.withExactArgs(1));
},
assert.exception(function () {
expectation(2, 2, 3);
}, "ExpectationError");
},
"should accept call with expected args": function () {
this.expectation.withExactArgs(1, 2, 3);
this.expectation(1, 2, 3);
"nots allow excessive args": function () {
var expectation = this.expectation;
expectation.withExactArgs(1, 2, 3);
assert(this.expectation.met());
},
assert.exception(function () {
expectation(1, 2, 3, 4);
}, "ExpectationError");
},
"should throw when called without args": function () {
var expectation = this.expectation;
expectation.withExactArgs(1, 2, 3);
"accepts call with no expected args": function () {
this.expectation.withExactArgs();
this.expectation();
assertException(function () {
expectation();
}, "ExpectationError");
},
assert(this.expectation.met());
},
"should throw when called with too few args": function () {
var expectation = this.expectation;
expectation.withExactArgs(1, 2, 3);
"nots allow excessive args with no expected args": function () {
var expectation = this.expectation;
expectation.withExactArgs();
assertException(function () {
expectation(1, 2);
}, "ExpectationError");
assert.exception(function () {
expectation(1, 2, 3);
}, "ExpectationError");
}
},
"should throw when called with wrong args": function () {
var expectation = this.expectation;
expectation.withExactArgs(1, 2, 3);
"on": {
"returns expectation for chaining": function () {
assert.same(this.expectation.on({}), this.expectation);
},
assertException(function () {
expectation(2, 2, 3);
}, "ExpectationError");
},
"allows calls on object": function () {
this.expectation.on(this);
this.expectation();
"should not allow excessive args": function () {
var expectation = this.expectation;
expectation.withExactArgs(1, 2, 3);
assert(this.expectation.met());
},
assertException(function () {
expectation(1, 2, 3, 4);
}, "ExpectationError");
}
});
"throws if called on wrong object": function () {
var expectation = this.expectation;
expectation.on({});
testCase("MockExpectationOnTest", {
setUp: expectationSetUp,
"should be method": function () {
assertFunction(this.expectation.on);
assert.exception(function () {
expectation();
}, "ExpectationError");
}
},
"should return expectation for chaining": function () {
assertSame(this.expectation, this.expectation.on({}));
},
"verify": {
"passs if met": function () {
sinon.stub(sinon.expectation, "pass");
var expectation = this.expectation;
"should allow calls on object": function () {
this.expectation.on(this);
this.expectation();
assert(this.expectation.met());
},
"should throw if called on wrong object": function () {
var expectation = this.expectation;
expectation.on({});
assertException(function () {
expectation();
}, "ExpectationError");
}
});
expectation.verify();
testCase("MockExpectationVerifyTest", {
setUp: expectationSetUp,
assert.equals(sinon.expectation.pass.callCount, 1);
sinon.expectation.pass.restore();
},
"should throw if not called enough times": function () {
var expectation = this.expectation;
"throws if not called enough times": function () {
var expectation = this.expectation;
assertException(function () {
expectation.verify();
}, "ExpectationError");
},
assert.exception(function () {
expectation.verify();
}, "ExpectationError");
},
"should throw readable error": function () {
var expectation = this.expectation;
"throws readable error": function () {
var expectation = this.expectation;
try {
expectation.verify();
fail("Expected to throw");
} catch (e) {
assertEquals("Expected myMeth([...]) once (never called)", e.message);
try {
expectation.verify();
buster.assertions.fail("Expected to throw");
} catch (e) {
assert.equals(e.message,
"Expected myMeth([...]) once (never called)");
}
}
}
});
},
testCase("MockVerifyTest", {
setUp: mockSetUp,
"verify": {
setUp: function () {
this.method = function () {};
this.object = { method: this.method };
this.mock = sinon.mock.create(this.object);
},
"should restore mocks": function () {
"restores mocks": function () {
this.object.method();

@@ -627,17 +613,28 @@ this.object.method.call(this.thisValue);

assertSame(this.method, this.object.method);
assert.same(this.object.method, this.method);
},
"should restore if not met": function () {
"passes verified mocks": function () {
sinon.stub(sinon.expectation, "pass");
this.mock.expects("method").once();
this.object.method();
this.mock.verify();
assert.equals(sinon.expectation.pass.callCount, 1);
sinon.expectation.pass.restore();
},
"restores if not met": function () {
var mock = this.mock;
mock.expects("method");
assertException(function () {
assert.exception(function () {
mock.verify();
}, "ExpectationError");
assertSame(this.method, this.object.method);
assert.same(this.object.method, this.method);
},
"should include all calls in error message": function () {
"includes all calls in error message": function () {
var mock = this.mock;

@@ -654,6 +651,7 @@ mock.expects("method").thrice();

assertEquals("Expected method([...]) thrice (never called)\nExpected method(42[, ...]) once (never called)", message);
assert.equals(message,
"Expected method([...]) thrice (never called)\nExpected method(42[, ...]) once (never called)");
},
"should include exact expected arguments in error message": function () {
"includes exact expected arguments in error message": function () {
var mock = this.mock;

@@ -669,6 +667,6 @@ mock.expects("method").once().withExactArgs(42);

assertEquals("Expected method(42) once (never called)", message);
assert.equals(message, "Expected method(42) once (never called)");
},
"should include received call count in error message": function () {
"includes received call count in error message": function () {
var mock = this.mock;

@@ -685,6 +683,6 @@ mock.expects("method").thrice().withExactArgs(42);

assertEquals("Expected method(42) thrice (called once)", message);
assert.equals(message, "Expected method(42) thrice (called once)");
},
"should include unexpected calls in error message": function () {
"includes unexpected calls in error message": function () {
var mock = this.mock;

@@ -700,7 +698,8 @@ mock.expects("method").thrice().withExactArgs(42);

assertEquals("Unexpected call: method()\n" +
" Expected method(42) thrice (never called)", message);
assert.equals(message,
"Unexpected call: method()\n" +
" Expected method(42) thrice (never called)");
},
"should include met expectations in error message": function () {
"includes met expectations in error message": function () {
var mock = this.mock;

@@ -718,8 +717,8 @@ mock.expects("method").once().withArgs(1);

assertEquals("Unexpected call: method()\n" +
" Expectation met: method(1[, ...]) once\n" +
" Expected method(42) thrice (never called)", message);
assert.equals(message, "Unexpected call: method()\n" +
" Expectation met: method(1[, ...]) once\n" +
" Expected method(42) thrice (never called)");
},
"should include met expectations in error message from verify": function () {
"includes met expectations in error message from verify": function () {
var mock = this.mock;

@@ -737,7 +736,7 @@ mock.expects("method").once().withArgs(1);

assertEquals("Expected method(42) thrice (never called)\n" +
"Expectation met: method(1[, ...]) once", message);
assert.equals(message, "Expected method(42) thrice (never called)\n" +
"Expectation met: method(1[, ...]) once");
},
"should report min calls in error message": function () {
"reports min calls in error message": function () {
var mock = this.mock;

@@ -753,6 +752,6 @@ mock.expects("method").atLeast(1);

assertEquals("Expected method([...]) at least once (never called)", message);
assert.equals(message, "Expected method([...]) at least once (never called)");
},
"should report max calls in error message": function () {
"reports max calls in error message": function () {
var mock = this.mock;

@@ -770,7 +769,7 @@ mock.expects("method").atMost(2);

assertEquals("Unexpected call: method()\n" +
" Expectation met: method([...]) at most twice", message);
assert.equals(message, "Unexpected call: method()\n" +
" Expectation met: method([...]) at most twice");
},
"should report min calls in met expectation": function () {
"reports min calls in met expectation": function () {
var mock = this.mock;

@@ -789,8 +788,8 @@ mock.expects("method").atLeast(1);

assertEquals("Unexpected call: method(2)\n" +
" Expectation met: method([...]) at least once\n" +
" Expectation met: method(2[, ...]) once", message);
assert.equals(message, "Unexpected call: method(2)\n" +
" Expectation met: method([...]) at least once\n" +
" Expectation met: method(2[, ...]) once");
},
"should report max and min calls in error messages": function () {
"reports max and min calls in error messages": function () {
var mock = this.mock;

@@ -806,39 +805,43 @@ mock.expects("method").atLeast(1).atMost(2);

assertEquals("Expected method([...]) at least once and at most twice " +
"(never called)", message);
assert.equals(message, "Expected method([...]) at least once and at most twice " +
"(never called)");
}
});
},
testCase("MockObjectTest", {
setUp: mockSetUp,
"mockObject": {
setUp: function () {
this.method = function () {};
this.object = { method: this.method };
this.mock = sinon.mock.create(this.object);
},
"should mock object method": function () {
"mocks object method": function () {
this.mock.expects("method");
assertFunction(this.object.method);
assertNotSame(this.method, this.object.method);
assert.isFunction(this.object.method);
refute.same(this.object.method, this.method);
},
"should revert mocked method": function () {
"reverts mocked method": function () {
this.mock.expects("method");
this.object.method.restore();
assertSame(this.method, this.object.method);
assert.same(this.object.method, this.method);
},
"should revert expectation": function () {
"reverts expectation": function () {
var method = this.mock.expects("method");
this.object.method.restore();
assertSame(this.method, this.object.method);
assert.same(this.object.method, this.method);
},
"should revert mock": function () {
"reverts mock": function () {
var method = this.mock.expects("method");
this.mock.restore();
assertSame(this.method, this.object.method);
assert.same(this.object.method, this.method);
},
"should verify mock": function () {
"verifies mock": function () {
var method = this.mock.expects("method");

@@ -848,3 +851,3 @@ this.object.method();

assertNoException(function () {
refute.exception(function () {
assert(mock.verify());

@@ -854,13 +857,13 @@ });

"should verify mock with unmet expectations": function () {
"verifies mock with unmet expectations": function () {
var method = this.mock.expects("method");
var mock = this.mock;
assertException(function () {
assert.exception(function () {
assert(mock.verify());
}, "ExpectationError");
}
});
},
testCase("MockMethodMultipleTimesTest", {
"mock method multiple times": {
setUp: function () {

@@ -875,6 +878,6 @@ this.thisValue = {};

"should queue expectations": function () {
"queues expectations": function () {
var object = this.object;
assertNoException(function () {
refute.exception(function () {
object.method();

@@ -884,7 +887,7 @@ });

"should start on next expectation when first is met": function () {
"starts on next expectation when first is met": function () {
var object = this.object;
object.method();
assertException(function () {
assert.exception(function () {
object.method();

@@ -894,3 +897,3 @@ }, "ExpectationError");

"should fail on last expectation": function () {
"fails on last expectation": function () {
var object = this.object;

@@ -900,3 +903,3 @@ object.method();

assertException(function () {
assert.exception(function () {
object.method();

@@ -906,3 +909,3 @@ }, "ExpectationError");

"should allow mock calls in any order": function () {
"allows mock calls in any order": function () {
var object = { method: function () {} };

@@ -913,44 +916,44 @@ var mock = sinon.mock(object);

assertNoException(function () {
refute.exception(function () {
object.method("Yeah");
});
assertNoException(function () {
refute.exception(function () {
object.method(42);
});
assertException(function () {
assert.exception(function () {
object.method(1);
});
assertNoException(function () {
refute.exception(function () {
object.method("Yeah");
});
assertException(function () {
assert.exception(function () {
object.method(42);
});
}
});
},
testCase("MockFunctionTest", {
"should return mock method": function () {
"mock function": {
"returns mock method": function () {
var mock = sinon.mock();
assertFunction(mock);
assertFunction(mock.atLeast);
assertFunction(mock.verify);
assert.isFunction(mock);
assert.isFunction(mock.atLeast);
assert.isFunction(mock.verify);
},
"should return mock object": function () {
"returns mock object": function () {
var mock = sinon.mock({});
assertObject(mock);
assertFunction(mock.expects);
assertFunction(mock.verify);
assert.isObject(mock);
assert.isFunction(mock.expects);
assert.isFunction(mock.verify);
}
});
},
testCase("MockExpectationYieldsTest", {
"should invoke only argument as callback": function () {
"yields": {
"invokes only argument as callback": function () {
var mock = sinon.mock().yields();

@@ -961,6 +964,6 @@ var spy = sinon.spy();

assert(spy.calledOnce);
assertEquals(0, spy.args[0].length);
assert.equals(spy.args[0].length, 0);
},
"should throw understandable error if no callback is passed": function () {
"throws understandable error if no callback is passed": function () {
var mock = sinon.mock().yields();

@@ -973,7 +976,6 @@ var spy = sinon.spy();

} catch (e) {
assertEquals("stub expected to yield, but no callback was passed.",
e.message);
assert.equals(e.message, "stub expected to yield, but no callback was passed.");
}
}
});
}());
}
});
/*jslint onevar: false*/
/*global testCase
XMLHttpRequest
ActiveXObject
window
setTimeout
sinon
assert
assertNull
assertNotNull
assertUndefined
assertArray
assertFalse
assertEquals
assertObject
assertSame
assertFunction*/
/*global XMLHttpRequest ActiveXObject window setTimeout sinon buster*/
/**

@@ -22,8 +7,8 @@ * @author Christian Johansen (christian@cjohansen.no)

*
* Copyright (c) 2010-2011 Christian Johansen
* Copyright (c) 2010-2012 Christian Johansen
*/
"use strict";
if (typeof require == "function" && typeof testCase == "undefined") {
var testCase = require("../test_case_shim");
if (typeof require == "function" && typeof module == "object") {
var buster = require("../runner");
var sinon = require("../../lib/sinon");

@@ -34,439 +19,380 @@ }

var supportsAjax = typeof XMLHttpRequest != "undefined" || typeof ActiveXObject != "undefined";
var globalXHR = global.XMLHttpRequest;
var globalAXO = global.ActiveXObject;
testCase("SandboxTest", {
"should be object": function () {
assertObject(sinon.sandbox);
buster.assertions.add("fakeServerWithClock", {
assert: function (obj, fakeServer) {
return buster.assertions.deepEqual(obj, fakeServer) &&
sinon.fakeServer.create.calledOn(sinon.fakeServerWithClock);
},
assertMessage: "Expected object ${0} to be a fake server with clock"
});
"should inherit collection": function () {
buster.testCase("sinon.sandbox", {
"inherits collection": function () {
assert(sinon.collection.isPrototypeOf(sinon.sandbox));
},
"should create sandboxes": function () {
"creates sandboxes": function () {
var sandbox = sinon.sandbox.create();
assertObject(sandbox);
assert.isObject(sandbox);
assert(sinon.sandbox.isPrototypeOf(sandbox));
}
});
testCase("SandboxUseFakeTimersTest", {
setUp: function () {
this.sandbox = sinon.create(sinon.sandbox);
},
tearDown: function () {
this.sandbox.clock.restore();
},
"useFakeTimers": {
setUp: function () {
this.sandbox = sinon.create(sinon.sandbox);
},
"should return clock object": function () {
var clock = this.sandbox.useFakeTimers();
tearDown: function () {
this.sandbox.clock.restore();
},
assertObject(clock);
assertFunction(clock.tick);
},
"returns clock object": function () {
var clock = this.sandbox.useFakeTimers();
"should expose clock property": function () {
this.sandbox.useFakeTimers();
assert.isObject(clock);
assert.isFunction(clock.tick);
},
assertObject(this.sandbox.clock);
assertFunction(this.sandbox.clock.tick);
},
"exposes clock property": function () {
this.sandbox.useFakeTimers();
"should use restorable clock": function () {
this.sandbox.useFakeTimers();
assert.isObject(this.sandbox.clock);
assert.isFunction(this.sandbox.clock.tick);
},
assertFunction(this.sandbox.clock.restore);
},
"uses restorable clock": function () {
this.sandbox.useFakeTimers();
"should pass arguments to sinon.useFakeTimers": sinon.test(function () {
this.stub(sinon, "useFakeTimers").returns({ restore: function () {} });
this.sandbox.useFakeTimers("Date", "setTimeout");
this.sandbox.useFakeTimers("setTimeout", "clearTimeout", "setInterval");
assert(sinon.useFakeTimers.calledWith("Date", "setTimeout"));
assert(sinon.useFakeTimers.calledWith("setTimeout", "clearTimeout", "setInterval"));
}),
"should add clock to fake collection": function () {
this.sandbox.useFakeTimers();
this.sandbox.restore();
assertSame(sinon.timers.setTimeout, setTimeout);
}
});
var globalXHR = global.XMLHttpRequest;
var globalAXO = global.ActiveXObject;
if (globalXHR || globalAXO) {
testCase("SandboxUseFakeXMLHttpRequestTest", {
setUp: function () {
this.sandbox = sinon.create(sinon.sandbox);
assert.isFunction(this.sandbox.clock.restore);
},
tearDown: function () {
this.sandbox.restore();
},
"passes arguments to sinon.useFakeTimers": sinon.test(function () {
this.stub(sinon, "useFakeTimers").returns({ restore: function () {} });
this.sandbox.useFakeTimers("Date", "setTimeout");
this.sandbox.useFakeTimers("setTimeout", "clearTimeout", "setInterval");
"should call sinon.useFakeXMLHttpRequest": sinon.test(function () {
this.stub(sinon, "useFakeXMLHttpRequest").returns({ restore: function () {} });
this.sandbox.useFakeXMLHttpRequest();
assert(sinon.useFakeXMLHttpRequest.called);
assert(sinon.useFakeTimers.calledWith("Date", "setTimeout"));
assert(sinon.useFakeTimers.calledWith("setTimeout", "clearTimeout", "setInterval"));
}),
"should add fake xhr to fake collection": function () {
this.sandbox.useFakeXMLHttpRequest();
"adds clock to fake collection": function () {
this.sandbox.useFakeTimers();
this.sandbox.restore();
assertSame(globalXHR, global.XMLHttpRequest);
assertSame(globalAXO, global.ActiveXObject);
assert.same(setTimeout, sinon.timers.setTimeout);
}
});
},
testCase("SandboxUseServer", {
setUp: function () {
this.sandbox = sinon.create(sinon.sandbox);
"fake XHR/server": {
// Causes problems in Chrome/Firefox
// TODO: Figure out why
// requiresSupportFor: {
// "XHR/ActiveXObject": globalXHR || globalAXO
// },
requiresSupportFor: {
"browser": typeof window !== "undefined"
},
tearDown: function () {
this.sandbox.restore();
},
"useFakeXMLHttpRequest": {
setUp: function () {
this.sandbox = sinon.create(sinon.sandbox);
},
"should return server": function () {
var server = this.sandbox.useFakeServer();
tearDown: function () {
this.sandbox.restore();
},
assertObject(server);
assertFunction(server.restore);
},
"calls sinon.useFakeXMLHttpRequest": sinon.test(function () {
this.stub(sinon, "useFakeXMLHttpRequest").returns({ restore: function () {} });
this.sandbox.useFakeXMLHttpRequest();
"should expose server property": function () {
var server = this.sandbox.useFakeServer();
assert(sinon.useFakeXMLHttpRequest.called);
}),
assertSame(server, this.sandbox.server);
},
"adds fake xhr to fake collection": function () {
this.sandbox.useFakeXMLHttpRequest();
this.sandbox.restore();
"should create server": function () {
var server = this.sandbox.useFakeServer();
assert(sinon.fakeServer.isPrototypeOf(server));
assert.same(global.XMLHttpRequest, globalXHR);
assert.same(global.ActiveXObject, globalAXO);
}
},
"should create server with cock": function () {
this.sandbox.serverPrototype = sinon.fakeServerWithClock;
var server = this.sandbox.useFakeServer();
"useFakeServer": {
setUp: function () {
this.sandbox = sinon.create(sinon.sandbox);
},
assert(sinon.fakeServerWithClock.isPrototypeOf(server));
},
tearDown: function () {
this.sandbox.restore();
},
"should add server to fake collection": function () {
this.sandbox.useFakeServer();
this.sandbox.restore();
"returns server": function () {
var server = this.sandbox.useFakeServer();
assertSame(globalXHR, global.XMLHttpRequest);
assertSame(globalAXO, global.ActiveXObject);
}
});
}
assert.isObject(server);
assert.isFunction(server.restore);
},
testCase("SandboxInjectTest", {
setUp: function () {
this.obj = {};
this.sandbox = sinon.create(sinon.sandbox);
},
"exposes server property": function () {
var server = this.sandbox.useFakeServer();
tearDown: function () {
this.sandbox.restore();
},
assert.same(this.sandbox.server, server);
},
"should inject spy, stub, mock": function () {
this.sandbox.inject(this.obj);
"creates server": function () {
var server = this.sandbox.useFakeServer();
assertFunction(this.obj.spy);
assertFunction(this.obj.stub);
assertFunction(this.obj.mock);
},
assert(sinon.fakeServer.isPrototypeOf(server));
},
"should not define clock, server and requests objects": function () {
this.sandbox.inject(this.obj);
"creates server with cock": function () {
this.sandbox.serverPrototype = sinon.fakeServerWithClock;
var server = this.sandbox.useFakeServer();
assertFalse("clock" in this.obj);
assertFalse("server" in this.obj);
assertFalse("requests" in this.obj);
},
assert(sinon.fakeServerWithClock.isPrototypeOf(server));
},
"should define clock when using fake time": function () {
this.sandbox.useFakeTimers();
this.sandbox.inject(this.obj);
"adds server to fake collection": function () {
this.sandbox.useFakeServer();
this.sandbox.restore();
assertFunction(this.obj.spy);
assertFunction(this.obj.stub);
assertFunction(this.obj.mock);
assertObject(this.obj.clock);
assertFalse("server" in this.obj);
assertFalse("requests" in this.obj);
},
"should define server and requests when using fake time": function () {
if (!supportsAjax) {
jstestdriver.console.log("Ajax unavailable, aborting");
return;
assert.same(global.XMLHttpRequest, globalXHR);
assert.same(global.ActiveXObject, globalAXO);
}
}
this.sandbox.useFakeServer();
this.sandbox.inject(this.obj);
assertFunction(this.obj.spy);
assertFunction(this.obj.stub);
assertFunction(this.obj.mock);
assertFalse("clock" in this.obj);
assertObject(this.obj.server);
assertEquals([], this.obj.requests);
},
"should define all possible fakes": function () {
if (!supportsAjax) {
jstestdriver.console.log("Ajax unavailable, aborting");
return;
}
"inject": {
setUp: function () {
this.obj = {};
this.sandbox = sinon.create(sinon.sandbox);
},
this.sandbox.useFakeServer();
this.sandbox.useFakeTimers();
this.sandbox.inject(this.obj);
tearDown: function () {
this.sandbox.restore();
},
var spy = sinon.spy();
setTimeout(spy, 10);
"injects spy, stub, mock": function () {
this.sandbox.inject(this.obj);
this.sandbox.clock.tick(10);
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
assert.isFunction(this.obj.spy);
assert.isFunction(this.obj.stub);
assert.isFunction(this.obj.mock);
},
assertFunction(this.obj.spy);
assertFunction(this.obj.stub);
assertFunction(this.obj.mock);
assert(spy.called);
assertObject(this.obj.server);
assertEquals([xhr], this.obj.requests);
},
"does not define clock, server and requests objects": function () {
this.sandbox.inject(this.obj);
"should return object": function () {
var injected = this.sandbox.inject({});
assert.isFalse("clock" in this.obj);
assert.isFalse("server" in this.obj);
assert.isFalse("requests" in this.obj);
},
assertObject(injected);
assertFunction(injected.spy);
}
});
"defines clock when using fake time": function () {
this.sandbox.useFakeTimers();
this.sandbox.inject(this.obj);
function assertSpy(obj) {
assertNotNull(obj);
assertFunction(obj.calledWith);
assertUndefined(obj.returns);
}
assert.isFunction(this.obj.spy);
assert.isFunction(this.obj.stub);
assert.isFunction(this.obj.mock);
assert.isObject(this.obj.clock);
assert.isFalse("server" in this.obj);
assert.isFalse("requests" in this.obj);
},
function assertStub(obj) {
assertNotNull(obj);
assertFunction(obj.calledWith);
assertFunction(obj.returns);
}
"should return object": function () {
var injected = this.sandbox.inject({});
function assertMock(obj) {
assertObject(obj);
assertFunction(obj.verify);
assertFunction(obj.expects);
}
assert.isObject(injected);
assert.isFunction(injected.spy);
},
function assertFakeServerWithClock(testCase, obj) {
assertEquals(testCase.fakeServer, obj);
assert(sinon.fakeServer.create.calledOn(sinon.fakeServerWithClock));
}
"ajax options": {
requiresSupportFor: { "ajax/browser": supportsAjax },
function boundTestCase() {
var properties = {
fn: function () {
properties.self = this;
properties.args = arguments;
properties.spy = this.spy;
properties.stub = this.stub;
properties.mock = this.mock;
properties.clock = this.clock;
properties.server = this.server;
properties.requests = this.requests;
properties.sandbox = this.sandbox;
}
};
"defines server and requests when using fake time": function () {
this.sandbox.useFakeServer();
this.sandbox.inject(this.obj);
return properties;
}
assert.isFunction(this.obj.spy);
assert.isFunction(this.obj.stub);
assert.isFunction(this.obj.mock);
assert.isFalse("clock" in this.obj);
assert.isObject(this.obj.server);
assert.equals(this.obj.requests, []);
},
testCase("ConfigurableSandboxTest", {
setUp: function () {
this.requests = [];
this.fakeServer = { requests: this.requests };
this.clock = {};
"should define all possible fakes": function () {
this.sandbox.useFakeServer();
this.sandbox.useFakeTimers();
this.sandbox.inject(this.obj);
sinon.stub(sinon, "useFakeTimers").returns(this.clock);
var spy = sinon.spy();
setTimeout(spy, 10);
if (sinon.fakeServer) {
sinon.stub(sinon.fakeServer, "create").returns(this.fakeServer);
}
},
this.sandbox.clock.tick(10);
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
tearDown: function () {
sinon.useFakeTimers.restore();
if (sinon.fakeServer) {
sinon.fakeServer.create.restore();
assert.isFunction(this.obj.spy);
assert.isFunction(this.obj.stub);
assert.isFunction(this.obj.mock);
assert(spy.called);
assert.isObject(this.obj.server);
assert.equals(this.obj.requests, [xhr]);
}
}
},
"should yield stub, mock as arguments": function () {
var sandbox = sinon.sandbox.create(sinon.getConfig({
injectIntoThis: false,
properties: ["stub", "mock"]
}));
"configurable sandbox": {
setUp: function () {
this.requests = [];
this.fakeServer = { requests: this.requests };
this.clock = {};
assertEquals(2, sandbox.args.length);
assertStub(sandbox.args[0]());
assertMock(sandbox.args[1]({}));
},
sinon.stub(sinon, "useFakeTimers").returns(this.clock);
"should yield spy, stub, mock as arguments": function () {
var sandbox = sinon.sandbox.create(sinon.getConfig({
injectIntoThis: false,
properties: ["spy", "stub", "mock"]
}));
if (sinon.fakeServer) {
sinon.stub(sinon.fakeServer, "create").returns(this.fakeServer);
}
},
assertSpy(sandbox.args[0]());
assertStub(sandbox.args[1]());
assertMock(sandbox.args[2]({}));
},
tearDown: function () {
sinon.useFakeTimers.restore();
if (sinon.fakeServer) { sinon.fakeServer.create.restore(); }
},
"should not yield server when not faking xhr": function () {
var sandbox = sinon.sandbox.create(sinon.getConfig({
injectIntoThis: false,
properties: ["server", "stub", "mock"],
useFakeServer: false
}));
"yields stub, mock as arguments": function () {
var sandbox = sinon.sandbox.create(sinon.getConfig({
injectIntoThis: false,
properties: ["stub", "mock"]
}));
assertEquals(2, sandbox.args.length);
assertStub(sandbox.args[0]());
assertMock(sandbox.args[1]({}));
},
assert.equals(sandbox.args.length, 2);
assert.stub(sandbox.args[0]());
assert.mock(sandbox.args[1]({}));
},
"should yield server when faking xhr": function () {
if (!supportsAjax) {
jstestdriver.console.log("Ajax unavailable, aborting");
return;
}
"yields spy, stub, mock as arguments": function () {
var sandbox = sinon.sandbox.create(sinon.getConfig({
injectIntoThis: false,
properties: ["spy", "stub", "mock"]
}));
var sandbox = sinon.sandbox.create(sinon.getConfig({
injectIntoThis: false,
properties: ["server", "stub", "mock"]
}));
assert.spy(sandbox.args[0]());
assert.stub(sandbox.args[1]());
assert.mock(sandbox.args[2]({}));
},
assertEquals(3, sandbox.args.length);
assertEquals(this.fakeServer, sandbox.args[0]);
assertStub(sandbox.args[1]());
assertMock(sandbox.args[2]({}));
},
"does not yield server when not faking xhr": function () {
var sandbox = sinon.sandbox.create(sinon.getConfig({
injectIntoThis: false,
properties: ["server", "stub", "mock"],
useFakeServer: false
}));
"should use serverWithClock when faking xhr": function () {
if (!supportsAjax) {
jstestdriver.console.log("Ajax unavailable, aborting");
return;
}
assert.equals(sandbox.args.length, 2);
assert.stub(sandbox.args[0]());
assert.mock(sandbox.args[1]({}));
},
var sandbox = sinon.sandbox.create(sinon.getConfig({
injectIntoThis: false,
properties: ["server"],
useFakeServer: sinon.fakeServerWithClock
}));
"ajax options": {
requiresSupportFor: { "ajax/browser": supportsAjax },
assertFakeServerWithClock(this, sandbox.args[0]);
},
"yields server when faking xhr": function () {
var sandbox = sinon.sandbox.create(sinon.getConfig({
injectIntoThis: false,
properties: ["server", "stub", "mock"]
}));
"should yield clock when faking timers": function () {
if (!supportsAjax) {
jstestdriver.console.log("Ajax unavailable, aborting");
return;
}
assert.equals(sandbox.args.length, 3);
assert.equals(sandbox.args[0], this.fakeServer);
assert.stub(sandbox.args[1]());
assert.mock(sandbox.args[2]({}));
},
var sandbox = sinon.sandbox.create(sinon.getConfig({
injectIntoThis: false,
properties: ["server", "clock"]
}));
"uses serverWithClock when faking xhr": function () {
var sandbox = sinon.sandbox.create(sinon.getConfig({
injectIntoThis: false,
properties: ["server"],
useFakeServer: sinon.fakeServerWithClock
}));
assertSame(this.fakeServer, sandbox.args[0]);
assertSame(this.clock, sandbox.args[1]);
},
assert.fakeServerWithClock(sandbox.args[0], this.fakeServer);
},
"should fake specified timers": function () {
var sandbox = sinon.sandbox.create(sinon.getConfig({
injectIntoThis: false,
properties: ["clock"],
useFakeTimers: ["Date", "setTimeout"]
}));
"yields clock when faking timers": function () {
var sandbox = sinon.sandbox.create(sinon.getConfig({
injectIntoThis: false,
properties: ["server", "clock"]
}));
assert(sinon.useFakeTimers.calledWith("Date", "setTimeout"));
},
assert.same(sandbox.args[0], this.fakeServer);
assert.same(sandbox.args[1], this.clock);
},
"should inject properties into object": function () {
if (!supportsAjax) {
jstestdriver.console.log("Ajax unavailable, aborting");
return;
}
"injects properties into object": function () {
var object = {};
var object = {};
var sandbox = sinon.sandbox.create(sinon.getConfig({
properties: ["server", "clock"],
injectInto: object
}));
var sandbox = sinon.sandbox.create(sinon.getConfig({
properties: ["server", "clock"],
injectInto: object
}));
assert.equals(sandbox.args.length, 0);
assert.equals(object.server, this.fakeServer);
assert.equals(object.clock, this.clock);
refute.defined(object.spy);
refute.defined(object.stub);
refute.defined(object.mock);
refute.defined(object.requests);
},
assertEquals(0, sandbox.args.length);
assertEquals(this.fakeServer, object.server);
assertEquals(this.clock, object.clock);
assertUndefined(object.spy);
assertUndefined(object.stub);
assertUndefined(object.mock);
assertUndefined(object.requests);
},
"should inject server and clock when only enabling them": function () {
var object = {};
"should inject server and clock when only enabling them": function () {
if (!supportsAjax) {
jstestdriver.console.log("Ajax unavailable, aborting");
return;
}
var sandbox = sinon.sandbox.create(sinon.getConfig({
injectInto: object,
useFakeTimers: true,
useFakeServer: true
}));
var object = {};
assert.equals(sandbox.args.length, 0);
assert.equals(object.server, this.fakeServer);
assert.equals(object.clock, this.clock);
assert.isFunction(object.spy);
assert.isFunction(object.stub);
assert.isFunction(object.mock);
assert.isArray(object.requests);
refute.defined(object.sandbox);
}
},
var sandbox = sinon.sandbox.create(sinon.getConfig({
injectInto: object,
useFakeTimers: true,
useFakeServer: true
}));
"fakes specified timers": function () {
var sandbox = sinon.sandbox.create(sinon.getConfig({
injectIntoThis: false,
properties: ["clock"],
useFakeTimers: ["Date", "setTimeout"]
}));
assertEquals(0, sandbox.args.length);
assertEquals(this.fakeServer, object.server);
assertEquals(this.clock, object.clock);
assertFunction(object.spy);
assertFunction(object.stub);
assertFunction(object.mock);
assertArray(object.requests);
assertUndefined(object.sandbox);
},
assert(sinon.useFakeTimers.calledWith("Date", "setTimeout"));
},
"should inject sandbox": function () {
var object = {};
"injects sandbox": function () {
var object = {};
var sandbox = sinon.sandbox.create(sinon.getConfig({
properties: ["sandbox", "spy"],
injectInto: object
}));
var sandbox = sinon.sandbox.create(sinon.getConfig({
properties: ["sandbox", "spy"],
injectInto: object
}));
assertEquals(0, sandbox.args.length);
assertFunction(object.spy);
assertObject(object.sandbox);
assert.equals(sandbox.args.length, 0);
assert.isFunction(object.spy);
assert.isObject(object.sandbox);
}
}
});
}(typeof global == "object" ? global : this));
}(typeof global == "object" ? global : window));
/*jslint onevar: false*/
/*globals testCase
sinon
fail
assert
assertUndefined
assertBoolean
assertFalse
assertFunction
assertSame
assertNotSame
assertEquals
assertNoException
assertException*/
/*globals sinon buster*/
/**

@@ -19,40 +7,27 @@ * @author Christian Johansen (christian@cjohansen.no)

*
* Copyright (c) 2010-2011 Christian Johansen
* Copyright (c) 2010-2012 Christian Johansen
*/
"use strict";
if (typeof require == "function" && typeof testCase == "undefined") {
var testCase = require("../test_case_shim");
if (typeof require === "function" && typeof module === "object") {
var buster = require("../runner");
var sinon = require("../../lib/sinon");
}
(function () {
testCase("StubCreateTest", {
"should return function": function () {
assertFunction(sinon.stub.create());
},
buster.testCase("sinon.stub", {
"is spy": function () {
var stub = sinon.stub.create();
"should be spy": function () {
var stub = sinon.stub.create();
assert.isFalse(stub.called);
assert.isFunction(stub.calledWith);
assert.isFunction(stub.calledOn);
},
assertBoolean(stub.called);
assertFunction(stub.calledWith);
assertFunction(stub.calledWith);
assertFunction(stub.calledOn);
}
});
testCase("StubReturnsTest", {
"should have returns method": function () {
"returns": {
"returns specified value": function () {
var stub = sinon.stub.create();
assertFunction(stub.returns);
},
"should return specified value": function () {
var stub = sinon.stub.create();
var object = {};
stub.returns(object);
assertSame(object, stub());
assert.same(stub(), object);
},

@@ -63,20 +38,14 @@

assertSame(stub, stub.returns(""));
assert.same(stub.returns(""), stub);
},
"should return undefined": function () {
"returns undefined": function () {
var stub = sinon.stub.create();
assertUndefined(stub());
refute.defined(stub());
}
});
testCase("StubReturnsArgTest", {
"should have returnsArg method": function() {
var stub = sinon.stub.create();
},
assertFunction(stub.returnsArg);
},
"should return argument at specified index": function() {
"returnsArg": {
"returns argument at specified index": function() {
var stub = sinon.stub.create();

@@ -86,15 +55,15 @@ stub.returnsArg(0);

assertSame(object, stub(object));
assert.same(stub(object), object);
},
"should return stub": function () {
"returns stub": function () {
var stub = sinon.stub.create();
assertSame(stub, stub.returnsArg(0));
assert.same(stub.returnsArg(0), stub);
},
"should throw if no index is specified": function () {
"throws if no index is specified": function () {
var stub = sinon.stub.create();
assertException(function () {
assert.exception(function () {
stub.returnsArg();

@@ -104,14 +73,47 @@ }, "TypeError");

"should throw if index is not number": function () {
"throws if index is not number": function () {
var stub = sinon.stub.create();
assertException(function () {
assert.exception(function () {
stub.returnsArg({});
}, "TypeError");
}
});
},
testCase("StubThrowsTest", {
"should throw specified exception": function () {
"returnsThis": {
"stub returns this": function () {
var instance = {};
instance.stub = sinon.stub.create();
instance.stub.returnsThis();
assert.same(instance.stub(), instance);
},
"stub returns undefined when detached": function () {
var stub = sinon.stub.create();
stub.returnsThis();
// Due to strict mode, would be `global` otherwise
assert.same(stub(), undefined);
},
"stub respects call/apply": function() {
var stub = sinon.stub.create();
stub.returnsThis();
var object = {};
assert.same(stub.call(object), object);
assert.same(stub.apply(object), object);
},
"returns stub": function () {
var stub = sinon.stub.create();
assert.same(stub.returnsThis(), stub);
}
},
"throws": {
"throws specified exception": function () {
var stub = sinon.stub.create();
var error = new Error();

@@ -124,13 +126,13 @@ stub.throws(error);

} catch (e) {
assertSame(error, e);
assert.same(e, error);
}
},
"should return stub": function () {
"returns stub": function () {
var stub = sinon.stub.create();
assertSame(stub, stub.throws({}));
assert.same(stub.throws({}), stub);
},
"should set type of exception to throw": function () {
"sets type of exception to throw": function () {
var stub = sinon.stub.create();

@@ -140,3 +142,3 @@ var exceptionType = "TypeError";

assertException(function () {
assert.exception(function () {
stub();

@@ -146,3 +148,3 @@ }, exceptionType);

"should specify exception message": function () {
"specifies exception message": function () {
var stub = sinon.stub.create();

@@ -154,9 +156,9 @@ var message = "Oh no!";

stub();
fail("Expected stub to throw");
buster.assertions.fail("Expected stub to throw");
} catch (e) {
assertEquals(message, e.message);
assert.equals(e.message, message);
}
},
"should not specify exception message if not provided": function () {
"does not specify exception message if not provided": function () {
var stub = sinon.stub.create();

@@ -167,19 +169,19 @@ stub.throws("Error");

stub();
fail("Expected stub to throw");
buster.assertions.fail("Expected stub to throw");
} catch (e) {
assertEquals("", e.message);
assert.equals(e.message, "");
}
},
"should throw generic error": function () {
"throws generic error": function () {
var stub = sinon.stub.create();
stub.throws();
assertException(function () {
assert.exception(function () {
stub();
}, "Error");
}
});
},
testCase("StubCallsArgTest", {
"callsArg": {
setUp: function () {

@@ -189,3 +191,3 @@ this.stub = sinon.stub.create();

"should call argument at specified index": function () {
"calls argument at specified index": function () {
this.stub.callsArg(2);

@@ -199,12 +201,10 @@ var callback = sinon.stub.create();

"should return stub": function () {
var stub = this.stub.callsArg(2);
assertFunction(stub);
"returns stub": function () {
assert.isFunction(this.stub.callsArg(2));
},
"should throw if argument at specified index is not callable": function () {
"throws if argument at specified index is not callable": function () {
this.stub.callsArg(0);
assertException(function () {
assert.exception(function () {
this.stub(1);

@@ -214,6 +214,6 @@ }, "TypeError");

"should throw if no index is specified": function () {
"throws if no index is specified": function () {
var stub = this.stub;
assertException(function () {
assert.exception(function () {
stub.callsArg();

@@ -223,12 +223,12 @@ }, "TypeError");

"should throw if index is not number": function () {
"throws if index is not number": function () {
var stub = this.stub;
assertException(function () {
assert.exception(function () {
stub.callsArg({});
}, "TypeError");
}
});
},
testCase("StubCallsArgWithTest", {
"callsArgWith": {
setUp: function () {

@@ -238,3 +238,3 @@ this.stub = sinon.stub.create();

"should call argument at specified index with provided args": function () {
"calls argument at specified index with provided args": function () {
var object = {};

@@ -249,9 +249,9 @@ this.stub.callsArgWith(1, object);

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

@@ -265,3 +265,3 @@ var callback = sinon.stub.create();

"should call callback wit multiple args": function () {
"calls callback with multiple args": function () {
var object = {};

@@ -277,6 +277,6 @@ var array = [];

"should throw if no index is specified": function () {
"throws if no index is specified": function () {
var stub = this.stub;
assertException(function () {
assert.exception(function () {
stub.callsArgWith();

@@ -286,20 +286,20 @@ }, "TypeError");

"should throw if index is not number": function () {
"throws if index is not number": function () {
var stub = this.stub;
assertException(function () {
assert.exception(function () {
stub.callsArgWith({});
}, "TypeError");
}
});
},
testCase("StubCallsArgOnTest", {
"callsArgOn": {
setUp: function () {
this.stub = sinon.stub.create();
this.fakeContext = {
foo: 'bar'
foo: "bar"
};
},
"should call argument at specified index": function () {
"calls argument at specified index": function () {
this.stub.callsArgOn(2, this.fakeContext);

@@ -314,12 +314,12 @@ var callback = sinon.stub.create();

"should return stub": function () {
"returns stub": function () {
var stub = this.stub.callsArgOn(2, this.fakeContext);
assertFunction(stub);
assert.isFunction(stub);
},
"should throw if argument at specified index is not callable": function () {
"throws if argument at specified index is not callable": function () {
this.stub.callsArgOn(0, this.fakeContext);
assertException(function () {
assert.exception(function () {
this.stub(1);

@@ -329,6 +329,6 @@ }, "TypeError");

"should throw if no index is specified": function () {
"throws if no index is specified": function () {
var stub = this.stub;
assertException(function () {
assert.exception(function () {
stub.callsArgOn();

@@ -338,6 +338,6 @@ }, "TypeError");

"should throw if no context is specified": function () {
"throws if no context is specified": function () {
var stub = this.stub;
assertException(function () {
assert.exception(function () {
stub.callsArgOn(3);

@@ -347,27 +347,26 @@ }, "TypeError");

"should throw if index is not number": function () {
"throws if index is not number": function () {
var stub = this.stub;
assertException(function () {
assert.exception(function () {
stub.callsArgOn(this.fakeContext, 2);
}, "TypeError");
},
"should throw if context is not an object": function () {
"throws if context is not an object": function () {
var stub = this.stub;
assertException(function () {
assert.exception(function () {
stub.callsArgOn(2, 2);
}, "TypeError");
}
});
},
testCase("StubCallsArgOnWithTest", {
"callsArgOnWith": {
setUp: function () {
this.stub = sinon.stub.create();
this.fakeContext = {
foo: 'bar'
};
this.fakeContext = { foo: "bar" };
},
"should call argument at specified index with provided args": function () {
"calls argument at specified index with provided args": function () {
var object = {};

@@ -383,9 +382,9 @@ this.stub.callsArgOnWith(1, this.fakeContext, object);

"should return function": function () {
"returns function": function () {
var stub = this.stub.callsArgOnWith(2, this.fakeContext, 3);
assertFunction(stub);
assert.isFunction(stub);
},
"should call callback without args": function () {
"calls callback without args": function () {
this.stub.callsArgOnWith(1, this.fakeContext);

@@ -400,3 +399,3 @@ var callback = sinon.stub.create();

"should call callback wit multiple args": function () {
"calls callback with multiple args": function () {
var object = {};

@@ -413,6 +412,6 @@ var array = [];

"should throw if no index is specified": function () {
"throws if no index is specified": function () {
var stub = this.stub;
assertException(function () {
assert.exception(function () {
stub.callsArgOnWith();

@@ -422,6 +421,6 @@ }, "TypeError");

"should throw if no context is specified": function () {
"throws if no context is specified": function () {
var stub = this.stub;
assertException(function () {
assert.exception(function () {
stub.callsArgOnWith(3);

@@ -431,6 +430,6 @@ }, "TypeError");

"should throw if index is not number": function () {
"throws if index is not number": function () {
var stub = this.stub;
assertException(function () {
assert.exception(function () {
stub.callsArgOnWith({});

@@ -440,12 +439,12 @@ }, "TypeError");

"should throw if context is not an object": function () {
"throws if context is not an object": function () {
var stub = this.stub;
assertException(function () {
assert.exception(function () {
stub.callsArgOnWith(2, 2);
}, "TypeError");
}
});
},
testCase("StubObjectMethodTest", {
"objectMethod": {
setUp: function () {

@@ -461,7 +460,3 @@ this.method = function () {};

"should be function": function () {
assertFunction(sinon.stub);
},
"should return function from wrapMethod": function () {
"returns function from wrapMethod": function () {
var wrapper = function () {};

@@ -474,6 +469,6 @@ sinon.wrapMethod = function () {

assertSame(wrapper, result);
assert.same(result, wrapper);
},
"should pass object and method to wrapMethod": function () {
"passes object and method to wrapMethod": function () {
var wrapper = function () {};

@@ -489,7 +484,7 @@ var args;

assertSame(this.object, args[0]);
assertSame("method", args[1]);
assert.same(args[0], this.object);
assert.same(args[1], "method");
},
"should use provided function as stub": function () {
"uses provided function as stub": function () {
var called = false;

@@ -505,14 +500,14 @@ var stub = sinon.stub(this.object, "method", function () {

"should wrap provided function": function () {
"wraps provided function": function () {
var customStub = function () {};
var stub = sinon.stub(this.object, "method", customStub);
assertNotSame(customStub, stub);
assertFunction(stub.restore);
refute.same(stub, customStub);
assert.isFunction(stub.restore);
},
"should throw if third argument is provided but not function": function () {
"throws if third argument is provided but not function": function () {
var object = this.object;
assertException(function () {
assert.exception(function () {
sinon.stub(object, "method", {});

@@ -525,4 +520,4 @@ }, "TypeError");

assertFunction(stub.returns);
assertFunction(stub.throws);
assert.isFunction(stub.returns);
assert.isFunction(stub.throws);
},

@@ -533,4 +528,4 @@

assertUndefined(stub.returns);
assertUndefined(stub.throws);
refute.defined(stub.returns);
refute.defined(stub.throws);
},

@@ -566,28 +561,28 @@

"should return standalone stub without arguments": function () {
"returns standalone stub without arguments": function () {
var stub = sinon.stub();
assertFunction(stub);
assertFalse(stub.called);
assert.isFunction(stub);
assert.isFalse(stub.called);
},
"should throw if property is not a function": function () {
"throws if property is not a function": function () {
var obj = { someProp: 42 };
assertException(function () {
assert.exception(function () {
sinon.stub(obj, "someProp");
});
assertEquals(42, obj.someProp);
assert.equals(obj.someProp, 42);
},
"should not stub function object": function () {
assertException(function () {
"does not stub function object": function () {
assert.exception(function () {
sinon.stub(function () {});
});
}
});
},
testCase("StubEverythingTest", {
"should stub all methods of object without property": function () {
"everything": {
"stubs all methods of object without property": function () {
var obj = {

@@ -601,8 +596,8 @@ func1: function () {},

assertFunction(obj.func1.restore);
assertFunction(obj.func2.restore);
assertFunction(obj.func3.restore);
assert.isFunction(obj.func1.restore);
assert.isFunction(obj.func2.restore);
assert.isFunction(obj.func3.restore);
},
"should stub prototype methods": function () {
"stubs prototype methods": function () {
function Obj() {}

@@ -614,35 +609,35 @@ Obj.prototype.func1 = function() {};

assertFunction(obj.func1.restore);
assert.isFunction(obj.func1.restore);
},
"should return object": function () {
"returns object": function () {
var object = {};
assertSame(object, sinon.stub(object));
assert.same(sinon.stub(object), object);
},
"should only stub functions": function () {
var object = {foo: 'bar'};
"only stubs functions": function () {
var object = { foo: "bar" };
sinon.stub(object);
assertEquals('bar', object.foo);
assert.equals(object.foo, "bar");
}
});
},
testCase("StubFunctionTest", {
"should throw if stubbing non-existent property": function () {
"function": {
"throws if stubbing non-existent property": function () {
var myObj = {};
assertException(function () {
assert.exception(function () {
sinon.stub(myObj, "ouch");
});
assertUndefined(myObj.ouch);
refute.defined(myObj.ouch);
},
"should have toString method": function () {
"has toString method": function () {
var obj = { meth: function () {} };
sinon.stub(obj, "meth");
assertEquals("meth", obj.meth.toString());
assert.equals(obj.meth.toString(), "meth");
},

@@ -653,3 +648,3 @@

assertEquals("stub", stub.toString());
assert.equals(stub.toString(), "stub");
},

@@ -662,8 +657,8 @@

assertEquals("meth", obj.meth.toString());
assert.equals(obj.meth.toString(), "meth");
}
});
},
testCase("StubYieldsTest", {
"should invoke only argument as callback": function () {
"yields": {
"invokes only argument as callback": function () {
var stub = sinon.stub().yields();

@@ -674,6 +669,6 @@ var spy = sinon.spy();

assert(spy.calledOnce);
assertEquals(0, spy.args[0].length);
assert.equals(spy.args[0].length, 0);
},
"should throw understandable error if no callback is passed": function () {
"throws understandable error if no callback is passed": function () {
var stub = sinon.stub().yields();

@@ -685,8 +680,7 @@

} catch (e) {
assertEquals("stub expected to yield, but no callback was passed.",
e.message);
assert.equals(e.message, "stub expected to yield, but no callback was passed.");
}
},
"should include stub name and actual arguments in error": function () {
"includes stub name and actual arguments in error": function () {
var myObj = { somethingAwesome: function () {} };

@@ -699,8 +693,8 @@ var stub = sinon.stub(myObj, "somethingAwesome").yields();

} catch (e) {
assertEquals("somethingAwesome expected to yield, but no callback " +
"was passed. Received [23, 42]", e.message);
assert.equals(e.message, "somethingAwesome expected to yield, but no callback " +
"was passed. Received [23, 42]");
}
},
"should invoke last argument as callback": function () {
"invokes last argument as callback": function () {
var stub = sinon.stub().yields();

@@ -711,6 +705,6 @@ var spy = sinon.spy();

assert(spy.calledOnce);
assertEquals(0, spy.args[0].length);
assert.equals(spy.args[0].length, 0);
},
"should invoke first of two callbacks": function () {
"invokes first of two callbacks": function () {
var stub = sinon.stub().yields();

@@ -725,3 +719,3 @@ var spy = sinon.spy();

"should invoke callback with arguments": function () {
"invokes callback with arguments": function () {
var obj = { id: 42 };

@@ -735,3 +729,3 @@ var stub = sinon.stub().yields(obj, "Crazy");

"should throw if callback throws": function () {
"throws if callback throws": function () {
var obj = { id: 42 };

@@ -741,17 +735,47 @@ var stub = sinon.stub().yields(obj, "Crazy");

assertException(function () {
assert.exception(function () {
stub(callback);
});
},
"plays nice with throws": function () {
var stub = sinon.stub().throws().yields();
var spy = sinon.spy();
assert.exception(function () {
stub(spy);
})
assert(spy.calledOnce);
},
"plays nice with returns": function () {
var obj = {};
var stub = sinon.stub().returns(obj).yields();
var spy = sinon.spy();
assert.same(stub(spy), obj);
assert(spy.calledOnce);
},
"plays nice with returnsArg": function () {
var stub = sinon.stub().returnsArg(0).yields();
var spy = sinon.spy();
assert.same(stub(spy), spy);
assert(spy.calledOnce);
},
"plays nice with returnsThis": function () {
var obj = {};
var stub = sinon.stub().returnsThis().yields();
var spy = sinon.spy();
assert.same(stub.call(obj, spy), obj);
assert(spy.calledOnce);
}
});
},
testCase("StubYieldsOnTest", {
"yieldsOn": {
setUp: function () {
this.stub = sinon.stub.create();
this.fakeContext = {
foo: 'bar'
};
this.fakeContext = { foo: "bar" };
},
"should invoke only argument as callback": function () {
"invokes only argument as callback": function () {
var spy = sinon.spy();

@@ -764,7 +788,7 @@

assert(spy.calledOn(this.fakeContext));
assertEquals(0, spy.args[0].length);
assert.equals(spy.args[0].length, 0);
},
"should throw if no context is specified": function () {
assertException(function () {
"throws if no context is specified": function () {
assert.exception(function () {
this.stub.yieldsOn();

@@ -774,3 +798,3 @@ }, "TypeError");

"should throw understandable error if no callback is passed": function () {
"throws understandable error if no callback is passed": function () {
this.stub.yieldsOn(this.fakeContext);

@@ -782,8 +806,7 @@

} catch (e) {
assertEquals("stub expected to yield, but no callback was passed.",
e.message);
assert.equals(e.message, "stub expected to yield, but no callback was passed.");
}
},
"should include stub name and actual arguments in error": function () {
"includes stub name and actual arguments in error": function () {
var myObj = { somethingAwesome: function () {} };

@@ -796,8 +819,8 @@ var stub = sinon.stub(myObj, "somethingAwesome").yieldsOn(this.fakeContext);

} catch (e) {
assertEquals("somethingAwesome expected to yield, but no callback " +
"was passed. Received [23, 42]", e.message);
assert.equals(e.message, "somethingAwesome expected to yield, but no callback " +
"was passed. Received [23, 42]");
}
},
"should invoke last argument as callback": function () {
"invokes last argument as callback": function () {
var spy = sinon.spy();

@@ -810,6 +833,6 @@ this.stub.yieldsOn(this.fakeContext);

assert(spy.calledOn(this.fakeContext));
assertEquals(0, spy.args[0].length);
assert.equals(spy.args[0].length, 0);
},
"should invoke first of two callbacks": function () {
"invokes first of two callbacks": function () {
var spy = sinon.spy();

@@ -826,3 +849,3 @@ var spy2 = sinon.spy();

"should invoke callback with arguments": function () {
"invokes callback with arguments": function () {
var obj = { id: 42 };

@@ -838,3 +861,3 @@ var spy = sinon.spy();

"should throw if callback throws": function () {
"throws if callback throws": function () {
var obj = { id: 42 };

@@ -845,11 +868,10 @@ var callback = sinon.stub().throws();

assertException(function () {
assert.exception(function () {
this.stub(callback);
});
}
});
},
// yieldsTo burde kunne kalles flere ganger?
testCase("StubYieldsToTest", {
"should yield to property of object argument": function () {
"yieldsTo": {
"yields to property of object argument": function () {
var stub = sinon.stub().yieldsTo("success");

@@ -861,6 +883,6 @@ var callback = sinon.spy();

assert(callback.calledOnce);
assertEquals(0, callback.args[0].length);
assert.equals(callback.args[0].length, 0);
},
"should throw understandable error if no object with callback is passed": function () {
"throws understandable error if no object with callback is passed": function () {
var stub = sinon.stub().yieldsTo("success");

@@ -872,9 +894,8 @@

} catch (e) {
assertEquals("stub expected to yield to 'success', but no object "+
"with such a property was passed.",
e.message);
assert.equals(e.message, "stub expected to yield to 'success', but no object "+
"with such a property was passed.");
}
},
"should include stub name and actual arguments in error": function () {
"includes stub name and actual arguments in error": function () {
var myObj = { somethingAwesome: function () {} };

@@ -887,9 +908,9 @@ var stub = sinon.stub(myObj, "somethingAwesome").yieldsTo("success");

} catch (e) {
assertEquals("somethingAwesome expected to yield to 'success', but " +
"no object with such a property was passed. " +
"Received [23, 42]", e.message);
assert.equals(e.message, "somethingAwesome expected to yield to 'success', but " +
"no object with such a property was passed. " +
"Received [23, 42]");
}
},
"should invoke property on last argument as callback": function () {
"invokes property on last argument as callback": function () {
var stub = sinon.stub().yieldsTo("success");

@@ -900,6 +921,6 @@ var callback = sinon.spy();

assert(callback.calledOnce);
assertEquals(0, callback.args[0].length);
assert.equals(callback.args[0].length, 0);
},
"should invoke first of two possible callbacks": function () {
"invokes first of two possible callbacks": function () {
var stub = sinon.stub().yieldsTo("error");

@@ -914,3 +935,3 @@ var callback = sinon.spy();

"should invoke callback with arguments": function () {
"invokes callback with arguments": function () {
var obj = { id: 42 };

@@ -924,3 +945,3 @@ var stub = sinon.stub().yieldsTo("success", obj, "Crazy");

"should throw if callback throws": function () {
"throws if callback throws": function () {
var obj = { id: 42 };

@@ -930,17 +951,15 @@ var stub = sinon.stub().yieldsTo("error", obj, "Crazy");

assertException(function () {
assert.exception(function () {
stub({ error: callback });
});
}
});
},
testCase("StubYieldsToOnTest", {
"yieldsToOn": {
setUp: function () {
this.stub = sinon.stub.create();
this.fakeContext = {
foo: 'bar'
};
this.fakeContext = { foo: "bar" };
},
"should yield to property of object argument": function () {
"yields to property of object argument": function () {
this.stub.yieldsToOn("success", this.fakeContext);

@@ -953,7 +972,7 @@ var callback = sinon.spy();

assert(callback.calledOn(this.fakeContext));
assertEquals(0, callback.args[0].length);
assert.equals(callback.args[0].length, 0);
},
"should throw if no context is specified": function () {
assertException(function () {
"throws if no context is specified": function () {
assert.exception(function () {
this.stub.yieldsToOn("success");

@@ -963,3 +982,3 @@ }, "TypeError");

"should throw understandable error if no object with callback is passed": function () {
"throws understandable error if no object with callback is passed": function () {
this.stub.yieldsToOn("success", this.fakeContext);

@@ -971,9 +990,8 @@

} catch (e) {
assertEquals("stub expected to yield to 'success', but no object "+
"with such a property was passed.",
e.message);
assert.equals(e.message, "stub expected to yield to 'success', but no object "+
"with such a property was passed.");
}
},
"should include stub name and actual arguments in error": function () {
"includes stub name and actual arguments in error": function () {
var myObj = { somethingAwesome: function () {} };

@@ -986,9 +1004,9 @@ var stub = sinon.stub(myObj, "somethingAwesome").yieldsToOn("success", this.fakeContext);

} catch (e) {
assertEquals("somethingAwesome expected to yield to 'success', but " +
"no object with such a property was passed. " +
"Received [23, 42]", e.message);
assert.equals(e.message, "somethingAwesome expected to yield to 'success', but " +
"no object with such a property was passed. " +
"Received [23, 42]");
}
},
"should invoke property on last argument as callback": function () {
"invokes property on last argument as callback": function () {
var callback = sinon.spy();

@@ -1001,6 +1019,6 @@

assert(callback.calledOn(this.fakeContext));
assertEquals(0, callback.args[0].length);
assert.equals(callback.args[0].length, 0);
},
"should invoke first of two possible callbacks": function () {
"invokes first of two possible callbacks": function () {
var callback = sinon.spy();

@@ -1017,3 +1035,3 @@ var callback2 = sinon.spy();

"should invoke callback with arguments": function () {
"invokes callback with arguments": function () {
var obj = { id: 42 };

@@ -1029,3 +1047,3 @@ var callback = sinon.spy();

"should throw if callback throws": function () {
"throws if callback throws": function () {
var obj = { id: 42 };

@@ -1036,45 +1054,260 @@ var callback = sinon.stub().throws();

assertException(function () {
assert.exception(function () {
this.stub({ error: callback });
});
}
});
},
testCase("StubWithArgsTest", {
"should define withArgs method": function () {
"withArgs": {
"defines withArgs method": function () {
var stub = sinon.stub();
assertFunction(stub.withArgs);
assert.isFunction(stub.withArgs);
},
"should create filtered stub": function () {
"creates filtered stub": function () {
var stub = sinon.stub();
var other = stub.withArgs(23);
assertNotSame(stub, other);
assertFunction(stub.returns);
assertFunction(other.returns);
refute.same(other, stub);
assert.isFunction(stub.returns);
assert.isFunction(other.returns);
},
"should filter return values based on arguments": function () {
"filters return values based on arguments": function () {
var stub = sinon.stub().returns(23);
stub.withArgs(42).returns(99);
assertEquals(23, stub());
assertEquals(99, stub(42));
assert.equals(stub(), 23);
assert.equals(stub(42), 99);
},
"should filter exceptions based on arguments": function () {
"filters exceptions based on arguments": function () {
var stub = sinon.stub().returns(23);
stub.withArgs(42).throws();
assertNoException(function () {
stub();
});
refute.exception(stub);
assert.exception(function () { stub(42); });
}
},
assertException(function () {
stub(42);
});
"callsArgAsync": {
setUp: function () {
this.stub = sinon.stub.create();
},
"passes call to callsArg": function () {
var spy = sinon.spy(this.stub, "callsArg");
this.stub.callsArgAsync(2);
assert(spy.calledWith(2));
},
"asynchronously calls argument at specified index": function (done) {
this.stub.callsArgAsync(2);
var callback = sinon.spy(done);
this.stub(1, 2, callback);
assert(!callback.called);
}
});
}());
},
"callsArgWithAsync": {
setUp: function () {
this.stub = sinon.stub.create();
},
"passes call to callsArgWith": function () {
var object = {};
sinon.spy(this.stub, "callsArgWith");
this.stub.callsArgWithAsync(1, object);
assert(this.stub.callsArgWith.calledWith(1, object));
},
"asynchronously calls callback at specified index with multiple args": function (done) {
var object = {};
var array = [];
this.stub.callsArgWithAsync(1, object, array);
var callback = sinon.spy(done(function () {
assert(callback.calledWith(object, array));
}));
this.stub(1, callback);
assert(!callback.called);
}
},
"callsArgOnAsync": {
setUp: function () {
this.stub = sinon.stub.create();
this.fakeContext = {
foo: "bar"
};
},
"passes call to callsArgOn": function () {
sinon.spy(this.stub, "callsArgOn");
this.stub.callsArgOnAsync(2, this.fakeContext);
assert(this.stub.callsArgOn.calledWith(2, this.fakeContext));
},
"asynchronously calls argument at specified index with specified context": function (done) {
var context = this.fakeContext;
this.stub.callsArgOnAsync(2, context);
var callback = sinon.spy(done(function () {
assert(callback.calledOn(context));
}));
this.stub(1, 2, callback);
assert(!callback.called);
}
},
"callsArgOnWithAsync": {
setUp: function () {
this.stub = sinon.stub.create();
this.fakeContext = { foo: "bar" };
},
"passes call to callsArgOnWith": function () {
var object = {};
sinon.spy(this.stub, "callsArgOnWith");
this.stub.callsArgOnWithAsync(1, this.fakeContext, object);
assert(this.stub.callsArgOnWith.calledWith(1, this.fakeContext, object));
},
"asynchronously calls argument at specified index with provided context and args": function (done) {
var object = {};
var context = this.fakeContext;
this.stub.callsArgOnWithAsync(1, context, object);
var callback = sinon.spy(done(function () {
assert(callback.calledOn(context))
assert(callback.calledWith(object));
}));
this.stub(1, callback);
assert(!callback.called);
}
},
"yieldsAsync": {
"passes call to yields": function () {
var stub = sinon.stub();
sinon.spy(stub, "yields");
stub.yieldsAsync();
assert(stub.yields.calledWith());
},
"asynchronously invokes only argument as callback": function (done) {
var stub = sinon.stub().yieldsAsync();
var spy = sinon.spy(done);
stub(spy);
assert(!spy.called);
}
},
"yieldsOnAsync": {
setUp: function () {
this.stub = sinon.stub.create();
this.fakeContext = { foo: "bar" };
},
"passes call to yieldsOn": function () {
var stub = sinon.stub();
sinon.spy(stub, "yieldsOn");
stub.yieldsOnAsync(this.fakeContext);
assert(stub.yieldsOn.calledWith(this.fakeContext));
},
"asynchronously invokes only argument as callback with given context": function (done) {
var context = this.fakeContext;
this.stub.yieldsOnAsync(context);
var spy = sinon.spy(done(function () {
assert(spy.calledOnce);
assert(spy.calledOn(context));
assert.equals(spy.args[0].length, 0);
}));
this.stub(spy);
assert(!spy.called);
}
},
"yieldsToAsync": {
"passes call to yieldsTo": function () {
var stub = sinon.stub();
sinon.spy(stub, "yieldsTo");
stub.yieldsToAsync("success");
assert(stub.yieldsTo.calledWith("success"));
},
"asynchronously yields to property of object argument": function (done) {
var stub = sinon.stub().yieldsToAsync("success");
var callback = sinon.spy(done(function () {
assert(callback.calledOnce);
assert.equals(callback.args[0].length, 0);
}));
stub({ success: callback });
assert(!callback.called);
}
},
"yieldsToOnAsync": {
setUp: function () {
this.stub = sinon.stub.create();
this.fakeContext = { foo: "bar" };
},
"passes call to yieldsToOn": function () {
var stub = sinon.stub();
sinon.spy(stub, "yieldsToOn");
stub.yieldsToOnAsync("success", this.fakeContext);
assert(stub.yieldsToOn.calledWith("success", this.fakeContext));
},
"asynchronously yields to property of object argument with given context": function (done) {
var context = this.fakeContext;
this.stub.yieldsToOnAsync("success", context);
var callback = sinon.spy(done(function () {
assert(callback.calledOnce);
assert(callback.calledOn(context));
assert.equals(callback.args[0].length, 0);
}));
this.stub({ success: callback });
assert(!callback.called);
}
}
});
/*jslint onevar: false*/
/*globals testCase
sinon
assert
assertFalse
assertUndefined
assertFunction
assertSame
assertNotSame
assertEquals
assertException*/
/*globals sinon buster*/
/**

@@ -16,216 +7,255 @@ * @author Christian Johansen (christian@cjohansen.no)

*
* Copyright (c) 2010-2011 Christian Johansen
* Copyright (c) 2010-2012 Christian Johansen
*/
"use strict";
if (typeof require == "function" && typeof testCase == "undefined") {
var testCase = require("../test_case_shim");
if (typeof require === "function" && typeof module === "object") {
var buster = require("../runner");
var sinon = require("../../lib/sinon");
}
(function () {
testCase("SinonTestCaseTest", {
"should be function": function () {
assertFunction(sinon.testCase);
},
buster.testCase("sinon.testCase", {
"throws without argument": function () {
assert.exception(function () {
sinon.testCase();
}, "TypeError");
},
"should return object": function () {
var tests = sinon.testCase({});
"throws without object": function () {
assert.exception(function () {
sinon.testCase(function () {});
}, "TypeError");
},
assertEquals({}, tests);
},
"only wraps functions with test prefix": sinon.test(function () {
this.spy(sinon, "test");
"should throw without argument": function () {
assertException(function () {
sinon.testCase();
}, "TypeError");
},
var testc = {
testA: function () {},
doB: function () {}
};
"should throw without object": function () {
assertException(function () {
sinon.testCase(function () {});
}, "TypeError");
},
sinon.testCase(testc);
"should only wrap functions with test prefix": sinon.test(function () {
this.spy(sinon, "test");
assert.isFunction(testc.doB);
assert(sinon.test.calledWith(testc.testA));
assert.isFalse(sinon.test.calledWith(testc.doB));
}),
var testc = {
testA: function () {},
doB: function () {}
};
"removes setUp method": function () {
var test = { setUp: function () {} };
var result = sinon.testCase(test);
sinon.testCase(testc);
refute.defined(result.setUp);
refute.defined(result["test setUp"]);
},
assertFunction(testc.doB);
assert(sinon.test.calledWith(testc.testA));
assertFalse(sinon.test.calledWith(testc.doB));
}),
"removes tearDown method": function () {
var test = { tearDown: function () {} };
var result = sinon.testCase(test);
"should remove setUp method": function () {
var test = { setUp: function () {} };
var result = sinon.testCase(test);
refute.defined(result.tearDown);
refute.defined(result["test tearDown"]);
},
assertUndefined(result.setUp);
assertUndefined(result["test setUp"]);
},
"calls setUp before any test": function () {
var test = { setUp: sinon.stub(), test: sinon.stub(), test2: sinon.stub() };
var result = sinon.testCase(test);
result.test();
result.test2();
"should remove tearDown method": function () {
var test = { tearDown: function () {} };
var result = sinon.testCase(test);
assert.equals(test.setUp.callCount, 2);
sinon.assert.called(test.test);
sinon.assert.called(test.test2);
},
assertUndefined(result.tearDown);
assertUndefined(result["test tearDown"]);
},
"calls tearDown after any test": function () {
var test = { tearDown: sinon.stub(), test: sinon.stub(), test2: sinon.stub() };
var result = sinon.testCase(test);
result.test();
result.test2();
"should call setUp before any test": function () {
var test = { setUp: sinon.stub(), test: sinon.stub(), test2: sinon.stub() };
var result = sinon.testCase(test);
result.test();
result.test2();
assertEquals(2, test.setUp.callCount);
refute.exception(function () {
sinon.assert.called(test.tearDown);
sinon.assert.called(test.test);
sinon.assert.called(test.test2);
},
});
},
"should call tearDown after any test": function () {
var test = { tearDown: sinon.stub(), test: sinon.stub(), test2: sinon.stub() };
var result = sinon.testCase(test);
"calls tearDown even if test throws": function () {
var test = { tearDown: sinon.stub(), test: sinon.stub().throws() };
var result = sinon.testCase(test);
assert.exception(function () {
result.test();
result.test2();
}, "Error");
sinon.assert.called(test.tearDown);
sinon.assert.called(test.test);
sinon.assert.called(test.test2);
},
sinon.assert.called(test.tearDown);
sinon.assert.called(test.test);
},
"should call tearDown even if test throws": function () {
var test = { tearDown: sinon.stub(), test: sinon.stub().throws() };
var result = sinon.testCase(test);
"calls setUp test tearDown in order": function () {
var testCase = {
setUp: sinon.stub(),
test: sinon.stub(),
tearDown: sinon.stub()
};
assertException(function () {
result.test();
}, "Error");
var result = sinon.testCase(testCase);
sinon.assert.called(test.tearDown);
sinon.assert.called(test.test);
},
try {
result.test();
} catch (e) {}
"should call setUp test tearDown in order": function () {
var testCase = {
setUp: sinon.stub(),
test: sinon.stub(),
tearDown: sinon.stub()
};
refute.exception(function () {
sinon.assert.callOrder(testCase.setUp, testCase.test, testCase.tearDown);
});
},
var result = sinon.testCase(testCase);
"calls in order when test throws": function () {
var testCase = {
setUp: sinon.stub(),
tearDown: sinon.stub(),
test: sinon.stub().throws()
};
try {
result.test();
} catch (e) {}
var result = sinon.testCase(testCase);
try {
result.test();
} catch (e) {}
refute.exception(function () {
sinon.assert.callOrder(testCase.setUp, testCase.test, testCase.tearDown);
},
});
},
"should call in order when test throws": function () {
var testCase = {
setUp: sinon.stub(),
tearDown: sinon.stub(),
test: sinon.stub().throws()
};
"unstubs objects after test is run": function () {
var myMeth = function () {};
var myObj = { meth: myMeth };
var result = sinon.testCase(testCase);
var testCase = sinon.testCase({
testA: function () {
this.stub(myObj, "meth");
try {
result.test();
} catch (e) {}
assert.isFunction(this.stub);
refute.same(myObj.meth, myMeth);
}
});
sinon.assert.callOrder(testCase.setUp, testCase.test, testCase.tearDown);
},
testCase.testA();
"should unstub objects after test is run": function () {
var myMeth = function () {};
var myObj = { meth: myMeth };
assert.same(myObj.meth, myMeth);
},
var testCase = sinon.testCase({
testA: function () {
this.stub(myObj, "meth");
"unstubs all methods of an objects after test is run": function () {
var myMeth = function () {};
var myMeth2 = function () {};
var myObj = { meth: myMeth, meth2: myMeth2 };
assertFunction(this.stub);
assertNotSame(myMeth, myObj.meth);
}
});
var testCase = sinon.testCase({
testA: function () {
this.stub(myObj);
testCase.testA();
assert.isFunction(this.stub);
assertSame(myMeth, myObj.meth);
},
refute.same(myObj.meth, myMeth);
refute.same(myObj.meth2, myMeth2);
}
});
"should unstub objects stubbed in setUp": function () {
var myMeth = function () {};
var myObj = { meth: myMeth };
testCase.testA();
var testCase = sinon.testCase({
setUp: function () {
this.stub(myObj, "meth");
},
assert.same(myObj.meth, myMeth);
assert.same(myObj.meth2, myMeth2);
},
testA: function () {
assertFunction(this.stub);
assertNotSame(myMeth, myObj.meth);
}
});
"unstubs objects stubbed in setUp": function () {
var myMeth = function () {};
var myObj = { meth: myMeth };
testCase.testA();
var testCase = sinon.testCase({
setUp: function () {
this.stub(myObj, "meth");
},
assertSame(myMeth, myObj.meth);
},
testA: function () {
assert.isFunction(this.stub);
refute.same(myObj.meth, myMeth);
}
});
"should allow the use of helper methods": function () {
var helper = sinon.spy();
testCase.testA();
var testC = sinon.testCase({
doIt: helper,
assert.same(myObj.meth, myMeth);
},
testIt: function () {
this.doIt();
}
});
"unstubs all methods of an objects stubbed in setUp": function () {
var myMeth = function () {};
var myMeth2 = function () {};
var myObj = { meth: myMeth, meth2: myMeth2 };
assertNoException(function () {
testC.testIt();
});
var testCase = sinon.testCase({
setUp: function () {
this.stub(myObj);
},
testA: function () {
assert.isFunction(this.stub);
assert(helper.calledOnce);
assert(helper.calledOn(testC));
},
refute.same(myObj.meth, myMeth);
refute.same(myObj.meth2, myMeth2);
}
});
"should return result of test function": function () {
var testC = sinon.testCase({
testIt: sinon.stub().returns(42)
});
testCase.testA();
assertEquals(42, testC.testIt());
},
assert.same(myObj.meth, myMeth);
assert.same(myObj.meth2, myMeth2);
},
"should return result of test function with setUp": function () {
var testC = sinon.testCase({
setUp: sinon.spy(),
testIt: sinon.stub().returns(42)
});
"allows the use of helper methods": function () {
var helper = sinon.spy();
assertEquals(42, testC.testIt());
},
var testC = sinon.testCase({
doIt: helper,
"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)
});
testIt: function () {
this.doIt();
}
});
assertEquals(42, testC.testIt());
}
});
}());
refute.exception(function () {
testC.testIt();
});
assert(helper.calledOnce);
assert(helper.calledOn(testC));
},
"returns result of test function": function () {
var testC = sinon.testCase({
testIt: sinon.stub().returns(42)
});
assert.equals(testC.testIt(), 42);
},
"returns result of test function with setUp": function () {
var testC = sinon.testCase({
setUp: sinon.spy(),
testIt: sinon.stub().returns(42)
});
assert.equals(testC.testIt(), 42);
},
"returns result of test function with setUp and teardown": function () {
var testC = sinon.testCase({
setUp: sinon.spy(),
tearDown: sinon.spy(),
testIt: sinon.stub().returns(42)
});
assert.equals(testC.testIt(), 42);
}
});
/*jslint onevar: false, eqeqeq: false, browser: true*/
/*globals testCase,
sinon,
fail,
assert,
assertNotNull,
assertUndefined,
assertArray,
assertEquals,
assertSame,
assertNotSame,
assertFunction,
assertObject,
assertException,
assertNoException*/
/*globals sinon, buster*/
/**

@@ -20,210 +7,191 @@ * @author Christian Johansen (christian@cjohansen.no)

*
* Copyright (c) 2010-2011 Christian Johansen
* Copyright (c) 2010-2012 Christian Johansen
*/
"use strict";
if (typeof require == "function" && typeof testCase == "undefined") {
var testCase = require("../test_case_shim");
if (typeof require == "function" && typeof module == "object") {
var buster = require("../runner");
var sinon = require("../../lib/sinon");
}
(function () {
var supportsAjax = typeof XMLHttpRequest != "undefined" || typeof ActiveXObject != "undefined";
buster.testCase("sinon.test", {
setUp: function () {
this.boundTestCase = function () {
var properties = {
fn: function () {
properties.self = this;
properties.args = arguments;
properties.spy = this.spy;
properties.stub = this.stub;
properties.mock = this.mock;
properties.clock = this.clock;
properties.server = this.server;
properties.requests = this.requests;
properties.sandbox = this.sandbox;
}
};
testCase("SinonTestTest", {
tearDown: function () {
sinon.config = {};
},
return properties;
};
},
"should throw if argument is not a function": function () {
assertException(function () {
sinon.test({});
});
},
tearDown: function () {
sinon.config = {};
},
"should proxy return value": function () {
var object = {};
"throws if argument is not a function": function () {
assert.exception(function () {
sinon.test({});
});
},
var result = sinon.test(function () {
return object;
})();
"proxys return value": function () {
var object = {};
assertSame(object, result);
},
var result = sinon.test(function () {
return object;
})();
"should stub inside sandbox": function () {
var method = function () {};
var object = { method: method };
assert.same(result, object);
},
sinon.test(function () {
this.stub(object, "method").returns(object);
"stubs inside sandbox": function () {
var method = function () {};
var object = { method: method };
assertSame(object, object.method());
}).call({});
},
sinon.test(function () {
this.stub(object, "method").returns(object);
"should restore stubs": function () {
var method = function () {};
var object = { method: method };
assert.same(object.method(), object);
}).call({});
},
sinon.test(function () {
this.stub(object, "method");
}).call({});
"restores stubs": function () {
var method = function () {};
var object = { method: method };
assertSame(method, object.method);
},
sinon.test(function () {
this.stub(object, "method");
}).call({});
"should throw when method throws": function () {
var method = function () {};
var object = { method: method };
assert.same(object.method, method);
},
assertException(function () {
sinon.test(function () {
this.stub(object, "method");
throw new Error();
}).call({});
}, "Error");
},
"restores stubs on all object methods": function() {
var method = function () {};
var method2 = function () {};
var object = { method: method, method2: method2 };
"should restore stub when method throws": function () {
var method = function () {};
var object = { method: method };
sinon.test(function () {
this.stub(object);
}).call({});
try {
sinon.test(function () {
this.stub(object, "method");
throw new Error();
}).call({});
} catch (e) {}
assert.same(object.method, method);
assert.same(object.method2, method2);
},
assertSame(method, object.method);
},
"throws when method throws": function () {
var method = function () {};
var object = { method: method };
"should mock inside sandbox": function () {
var method = function () {};
var object = { method: method };
assert.exception(function () {
sinon.test(function () {
this.stub(object, "method");
throw new Error();
}).call({});
}, "Error");
},
"restores stub when method throws": function () {
var method = function () {};
var object = { method: method };
try {
sinon.test(function () {
this.mock(object).expects("method").returns(object);
assertSame(object, object.method());
this.stub(object, "method");
throw new Error();
}).call({});
},
} catch (e) {}
"should verify mocks": function () {
var method = function () {};
var object = { method: method };
assert.same(object.method, method);
},
assertException(function () {
sinon.test(function () {
this.mock(object).expects("method");
}).call({});
}, "ExpectationError");
"mocks inside sandbox": function () {
var method = function () {};
var object = { method: method };
assertSame(method, object.method);
},
sinon.test(function () {
this.mock(object).expects("method").returns(object);
"should restore mocks": function () {
var method = function () {};
var object = { method: method };
assert.same(object.method(), object);
}).call({});
},
try {
sinon.test(function () {
this.mock(object).expects("method");
}).call({});
} catch (e) {}
"verifies mocks": function () {
var method = function () {};
var object = { method: method };
assertSame(method, object.method);
},
assert.exception(function () {
sinon.test(function () {
this.mock(object).expects("method");
}).call({});
}, "ExpectationError");
"should restore mock when method throws": function () {
var method = function () {};
var object = { method: method };
assert.same(object.method, method);
},
try {
sinon.test(function () {
this.mock(object).expects("method").never();
object.method();
}).call({});
} catch (e) {}
"restores mocks": function () {
var method = function () {};
var object = { method: method };
assertSame(method, object.method);
},
try {
sinon.test(function () {
this.mock(object).expects("method");
}).call({});
} catch (e) {}
"should append helpers after normal arguments": function () {
var object = { method: function () {} };
assert.same(object.method, method);
},
sinon.config = {
injectIntoThis: false,
properties: ["stub", "mock"]
};
"restores mock when method throws": function () {
var method = function () {};
var object = { method: method };
sinon.test(function (obj, stub, mock) {
mock(object).expects("method").once();
try {
sinon.test(function () {
this.mock(object).expects("method").never();
object.method();
}).call({});
} catch (e) {}
assertSame(object, obj);
})(object);
},
assert.same(object.method, method);
},
"should maintain the this value": function () {
var testCase = {
someTest: sinon.test(function (obj, stub, mock) {
return this;
})
};
"appends helpers after normal arguments": function () {
var object = { method: function () {} };
assertSame(testCase, testCase.someTest());
}
});
sinon.config = {
injectIntoThis: false,
properties: ["stub", "mock"]
};
function assertSpy(obj) {
assertNotNull(obj);
assertFunction(obj.calledWith);
assertUndefined(obj.returns);
}
sinon.test(function (obj, stub, mock) {
mock(object).expects("method").once();
object.method();
function assertStub(obj) {
assertNotNull(obj);
assertFunction(obj.calledWith);
assertFunction(obj.returns);
}
assert.same(obj, object);
})(object);
},
function assertMock(obj) {
assertObject(obj);
assertFunction(obj.verify);
assertFunction(obj.expects);
}
function assertFakeServer(server) {
assertObject(server);
assertArray(server.requests);
assertFunction(server.respondWith);
}
function assertClock(clock) {
assertObject(clock);
assertFunction(clock.tick);
assertFunction(clock.setTimeout);
}
function boundTestCase() {
var properties = {
fn: function () {
properties.self = this;
properties.args = arguments;
properties.spy = this.spy;
properties.stub = this.stub;
properties.mock = this.mock;
properties.clock = this.clock;
properties.server = this.server;
properties.requests = this.requests;
properties.sandbox = this.sandbox;
}
"maintains the this value": function () {
var testCase = {
someTest: sinon.test(function (obj, stub, mock) {
return this;
})
};
return properties;
}
assert.same(testCase.someTest(), testCase);
},
testCase("ConfigurableTestWithSandboxTest", {
"configurable test with sandbox": {
tearDown: function () {

@@ -233,3 +201,3 @@ sinon.config = {};

"should yield stub, mock as arguments": function () {
"yields stub, mock as arguments": function () {
var stubbed, mocked;

@@ -247,10 +215,10 @@ var obj = { meth: function () {} };

assertEquals(2, arguments.length);
assert.equals(arguments.length, 2);
})();
assertStub(stubbed);
assertMock(mocked);
assert.stub(stubbed);
assert.mock(mocked);
},
"should yield spy, stub, mock as arguments": function () {
"yields spy, stub, mock as arguments": function () {
var spied, stubbed, mocked;

@@ -270,11 +238,11 @@ var obj = { meth: function () {} };

assertEquals(3, arguments.length);
assert.equals(arguments.length, 3);
})();
assertSpy(spied);
assertStub(stubbed);
assertMock(mocked);
assert.spy(spied);
assert.stub(stubbed);
assert.mock(mocked);
},
"should not yield server when not faking xhr": function () {
"does not yield server when not faking xhr": function () {
var stubbed, mocked;

@@ -293,59 +261,103 @@ var obj = { meth: function () {} };

assertEquals(2, arguments.length);
assert.equals(arguments.length, 2);
})();
assertStub(stubbed);
assertMock(mocked);
assert.stub(stubbed);
assert.mock(mocked);
},
"should yield server when faking xhr": function () {
if (!supportsAjax) {
jstestdriver.console.log("Ajax unavailable, aborting");
return;
}
"browser options": {
requiresSupportFor: {
"ajax/browser": typeof XMLHttpRequest != "undefined" || typeof ActiveXObject != "undefined"
},
var stubbed, mocked, server;
var obj = { meth: function () {} };
"yields server when faking xhr": function () {
var stubbed, mocked, server;
var obj = { meth: function () {} };
sinon.config = {
injectIntoThis: false,
properties: ["server", "stub", "mock"]
};
sinon.config = {
injectIntoThis: false,
properties: ["server", "stub", "mock"]
};
sinon.test(function (serv, stub, mock) {
server = serv;
stubbed = stub(obj, "meth");
mocked = mock(obj);
sinon.test(function (serv, stub, mock) {
server = serv;
stubbed = stub(obj, "meth");
mocked = mock(obj);
assertEquals(3, arguments.length);
})();
assert.equals(arguments.length, 3);
})();
assertFakeServer(server);
assertStub(stubbed);
assertMock(mocked);
},
assert.fakeServer(server);
assert.stub(stubbed);
assert.mock(mocked);
},
"should use serverWithClock when faking xhr": function () {
if (!supportsAjax) {
jstestdriver.console.log("Ajax unavailable, aborting");
return;
}
"uses serverWithClock when faking xhr": function () {
var server;
var server;
sinon.config = {
injectIntoThis: false,
properties: ["server"],
useFakeServer: sinon.fakeServerWithClock
};
sinon.config = {
injectIntoThis: false,
properties: ["server"],
useFakeServer: sinon.fakeServerWithClock
};
sinon.test(function (serv) {
server = serv;
})();
sinon.test(function (serv) {
server = serv;
})();
assert.fakeServer(server);
assert(sinon.fakeServerWithClock.isPrototypeOf(server));
},
assertFakeServer(server);
assert(sinon.fakeServerWithClock.isPrototypeOf(server));
"injects properties into object": function () {
var testCase = this.boundTestCase();
var obj = {};
sinon.config = {
injectIntoThis: false,
injectInto: obj,
properties: ["server", "clock", "spy", "stub", "mock", "requests"]
};
sinon.test(testCase.fn).call(testCase);
assert.equals(testCase.args.length, 0);
refute.defined(testCase.server);
refute.defined(testCase.clock);
refute.defined(testCase.spy);
refute.defined(testCase.stub);
refute.defined(testCase.mock);
refute.defined(testCase.requests);
assert.fakeServer(obj.server);
assert.clock(obj.clock);
assert.isFunction(obj.spy);
assert.isFunction(obj.stub);
assert.isFunction(obj.mock);
assert.isArray(obj.requests);
},
"injects server and clock when only enabling them": function () {
var testCase = this.boundTestCase();
var obj = {};
sinon.config = {
useFakeTimers: true,
useFakeServer: true
};
sinon.test(testCase.fn).call(testCase);
assert.equals(testCase.args.length, 0);
assert.isFunction(testCase.spy);
assert.isFunction(testCase.stub);
assert.isFunction(testCase.mock);
assert.fakeServer(testCase.server);
assert.isArray(testCase.requests);
assert.clock(testCase.clock);
refute.defined(testCase.sandbox);
}
},
"should yield clock when faking timers": function () {
"yields clock when faking timers": function () {
var clock;

@@ -360,9 +372,9 @@

clock = c;
assertEquals(1, arguments.length);
assert.equals(arguments.length, 1);
})();
assertClock(clock);
assert.clock(clock);
},
"should fake specified timers": function () {
"fakes specified timers": function () {
var props;

@@ -387,11 +399,11 @@

assertNotSame(sinon.timers.Date, props.Date);
assertNotSame(sinon.timers.setTimeout, props.setTimeout);
assertSame(sinon.timers.clearTimeout, props.clearTimeout);
assertSame(sinon.timers.setInterval, props.setInterval);
assertSame(sinon.timers.clearInterval, props.clearInterval);
refute.same(props.Date, sinon.timers.Date);
refute.same(props.setTimeout, sinon.timers.setTimeout);
assert.same(props.clearTimeout, sinon.timers.clearTimeout);
assert.same(props.setInterval, sinon.timers.setInterval);
assert.same(props.clearInterval, sinon.timers.clearInterval);
},
"should inject properties into test case": function () {
var testCase = boundTestCase();
"injects properties into test case": function () {
var testCase = this.boundTestCase();

@@ -404,86 +416,28 @@ sinon.config = {

assertSame(testCase, testCase.self);
assertEquals(0, testCase.args.length);
assertClock(testCase.clock);
assertUndefined(testCase.spy);
assertUndefined(testCase.stub);
assertUndefined(testCase.mock);
assert.same(testCase.self, testCase);
assert.equals(testCase.args.length, 0);
assert.clock(testCase.clock);
refute.defined(testCase.spy);
refute.defined(testCase.stub);
refute.defined(testCase.mock);
},
"should inject properties into object": function () {
if (!supportsAjax) {
jstestdriver.console.log("Ajax unavailable, aborting");
return;
}
var testCase = boundTestCase();
"injects functions into test case by default": function () {
var testCase = this.boundTestCase();
var obj = {};
sinon.config = {
injectIntoThis: false,
injectInto: obj,
properties: ["server", "clock", "spy", "stub", "mock", "requests"]
};
sinon.test(testCase.fn).call(testCase);
assertEquals(0, testCase.args.length);
assertUndefined(testCase.server);
assertUndefined(testCase.clock);
assertUndefined(testCase.spy);
assertUndefined(testCase.stub);
assertUndefined(testCase.mock);
assertUndefined(testCase.requests);
assertFakeServer(obj.server);
assertClock(obj.clock);
assertFunction(obj.spy);
assertFunction(obj.stub);
assertFunction(obj.mock);
assertArray(obj.requests);
assert.equals(testCase.args.length, 0);
assert.isFunction(testCase.spy);
assert.isFunction(testCase.stub);
assert.isFunction(testCase.mock);
assert.isObject(testCase.clock);
},
"should inject functions into test case by default": function () {
var testCase = boundTestCase();
"injects sandbox": function () {
var testCase = this.boundTestCase();
var obj = {};
sinon.test(testCase.fn).call(testCase);
assertEquals(0, testCase.args.length);
assertFunction(testCase.spy);
assertFunction(testCase.stub);
assertFunction(testCase.mock);
assertObject(testCase.clock);
},
"should inject server and clock when only enabling them": function () {
if (!supportsAjax) {
jstestdriver.console.log("Ajax unavailable, aborting");
return;
}
var testCase = boundTestCase();
var obj = {};
sinon.config = {
useFakeTimers: true,
useFakeServer: true
};
sinon.test(testCase.fn).call(testCase);
assertEquals(0, testCase.args.length);
assertFunction(testCase.spy);
assertFunction(testCase.stub);
assertFunction(testCase.mock);
assertFakeServer(testCase.server);
assertArray(testCase.requests);
assertClock(testCase.clock);
assertUndefined(testCase.sandbox);
},
"should inject sandbox": function () {
var testCase = boundTestCase();
var obj = {};
sinon.config = {
properties: ["sandbox", "spy"]

@@ -494,8 +448,8 @@ };

assertEquals(0, testCase.args.length);
assertFunction(testCase.spy);
assertObject(testCase.sandbox);
assert.equals(testCase.args.length, 0);
assert.isFunction(testCase.spy);
assert.isObject(testCase.sandbox);
},
"should use sinon.test to fake time": function () {
"uses sinon.test to fake time": function () {
sinon.config = {

@@ -521,3 +475,3 @@ useFakeTimers: true

}
});
}());
}
});
/*jslint onevar: false, eqeqeq: false, browser: true*/
/*globals window
jstestdriver
testCase
sinon
assert
assertSame
assertNotSame
assertEquals
assertTrue
assertFalse
assertNull
assertNotNull
assertException
assertNoException
assertUndefined
assertObject
assertFunction*/
/*globals window sinon buster*/
/**

@@ -23,7 +7,7 @@ * @author Christian Johansen (christian@cjohansen.no)

*
* Copyright (c) 2011 Christian Johansen
* Copyright (c) 2011-2012 Christian Johansen
*/
"use strict";
testCase("EventTargetTest", {
buster.testCase("sinon.EventTarget", {
setUp: function () {

@@ -33,3 +17,3 @@ this.target = sinon.extend({}, sinon.EventTarget);

"should notify event listener": function () {
"notifies event listener": function () {
var listener = sinon.spy();

@@ -45,3 +29,3 @@ this.target.addEventListener("dummy", listener);

"should notify event listener with target as this": function () {
"notifies event listener with target as this": function () {
var listener = sinon.spy();

@@ -56,3 +40,3 @@ this.target.addEventListener("dummy", listener);

"should notify all event listeners": function () {
"notifies all event listeners": function () {
var listeners = [sinon.spy(), sinon.spy()];

@@ -69,3 +53,3 @@ this.target.addEventListener("dummy", listeners[0]);

"should notify event listener of type listener": function () {
"notifies event listener of type listener": function () {
var listener = { handleEvent: sinon.spy() };

@@ -79,3 +63,3 @@ this.target.addEventListener("dummy", listener);

"should not notify listeners of other events": function () {
"does not notify listeners of other events": function () {
var listeners = [sinon.spy(), sinon.spy()];

@@ -87,6 +71,6 @@ this.target.addEventListener("dummy", listeners[0]);

assertFalse(listeners[1].called);
assert.isFalse(listeners[1].called);
},
"should not notify unregistered listeners": function () {
"does not notify unregistered listeners": function () {
var listener = sinon.spy();

@@ -98,6 +82,6 @@ this.target.addEventListener("dummy", listener);

assertFalse(listener.called);
assert.isFalse(listener.called);
},
"should notify existing listeners after removing one": function () {
"notifies existing listeners after removing one": function () {
var listeners = [sinon.spy(), sinon.spy(), sinon.spy()];

@@ -115,3 +99,3 @@ this.target.addEventListener("dummy", listeners[0]);

"should return false when event.preventDefault is not called": function () {
"returns false when event.preventDefault is not called": function () {
this.target.addEventListener("dummy", sinon.spy());

@@ -122,6 +106,6 @@

assertFalse(result);
assert.isFalse(result);
},
"should return true when event.preventDefault is called": function () {
"returns true when event.preventDefault is called": function () {
this.target.addEventListener("dummy", function (e) {

@@ -133,4 +117,4 @@ e.preventDefault();

assertTrue(result);
assert.isTrue(result);
}
});
/*jslint onevar: false, browser: false, regexp: false, browser: true*/
/*globals testCase
sinon
window
assert
assertSame
assertEquals
assertTrue
assertFalse
assertNull
assertException
assertNoException
assertUndefined
assertObject
assertFunction*/
/*globals sinon window buster*/
/**

@@ -20,7 +7,7 @@ * @author Christian Johansen (christian@cjohansen.no)

*
* Copyright (c) 2010-2011 Christian Johansen
* Copyright (c) 2010-2012 Christian Johansen
*/
"use strict";
testCase("ServerCreateTest", {
buster.testCase("sinon.fakeServer", {
tearDown: function () {

@@ -30,16 +17,9 @@ this.server.restore();

"should return server object": function () {
"provides restore method": function () {
this.server = sinon.fakeServer.create();
assertObject(this.server);
assert(sinon.fakeServer.isPrototypeOf(this.server));
assert.isFunction(this.server.restore);
},
"should provide restore method": function () {
this.server = sinon.fakeServer.create();
assertFunction(this.server.restore);
},
"should fake XMLHttpRequest": sinon.test(function () {
"fakes XMLHttpRequest": sinon.test(function () {
this.stub(sinon, "useFakeXMLHttpRequest").returns({

@@ -54,3 +34,3 @@ restore: this.stub()

"should mirror FakeXMLHttpRequest restore method": sinon.test(function () {
"mirrors FakeXMLHttpRequest restore method": sinon.test(function () {
this.server = sinon.fakeServer.create();

@@ -61,575 +41,571 @@ var restore = this.stub(sinon.FakeXMLHttpRequest, "restore");

assert(restore.called);
})
});
}),
testCase("ServerRequestsTest", {
setUp: function () {
this.server = sinon.fakeServer.create();
},
"requests": {
setUp: function () {
this.server = sinon.fakeServer.create();
},
tearDown: function () {
this.server.restore();
},
tearDown: function () {
this.server.restore();
},
"should collect objects created with fake XHR": function () {
var xhrs = [new sinon.FakeXMLHttpRequest(), new sinon.FakeXMLHttpRequest()];
"collects objects created with fake XHR": function () {
var xhrs = [new sinon.FakeXMLHttpRequest(), new sinon.FakeXMLHttpRequest()];
assertEquals(xhrs, this.server.requests);
},
assert.equals(this.server.requests, xhrs);
},
"should collect xhr objects through addRequest": function () {
this.server.addRequest = sinon.spy();
var xhr = new sinon.FakeXMLHttpRequest();
"collects xhr objects through addRequest": function () {
this.server.addRequest = sinon.spy();
var xhr = new sinon.FakeXMLHttpRequest();
assert(this.server.addRequest.calledWith(xhr));
},
assert(this.server.addRequest.calledWith(xhr));
},
"should observe onSend on requests": function () {
var xhrs = [new sinon.FakeXMLHttpRequest(), new sinon.FakeXMLHttpRequest()];
"observes onSend on requests": function () {
var xhrs = [new sinon.FakeXMLHttpRequest(), new sinon.FakeXMLHttpRequest()];
assertFunction(xhrs[0].onSend);
assertFunction(xhrs[1].onSend);
},
assert.isFunction(xhrs[0].onSend);
assert.isFunction(xhrs[1].onSend);
},
"onSend should call handleRequest with request object": function () {
var xhr = new sinon.FakeXMLHttpRequest();
xhr.open("GET", "/");
sinon.spy(this.server, "handleRequest");
"onSend should call handleRequest with request object": function () {
var xhr = new sinon.FakeXMLHttpRequest();
xhr.open("GET", "/");
sinon.spy(this.server, "handleRequest");
xhr.send();
xhr.send();
assert(this.server.handleRequest.called);
assert(this.server.handleRequest.calledWith(xhr));
}
});
testCase("ServerHandleRequestTest", {
setUp: function () {
this.server = sinon.fakeServer.create();
assert(this.server.handleRequest.called);
assert(this.server.handleRequest.calledWith(xhr));
}
},
tearDown: function () {
this.server.restore();
},
"handleRequest": {
setUp: function () {
this.server = sinon.fakeServer.create();
},
"should respond to synchronous requests": function () {
var xhr = new sinon.FakeXMLHttpRequest();
xhr.open("GET", "/", false);
sinon.spy(xhr, "respond");
tearDown: function () {
this.server.restore();
},
xhr.send();
"responds to synchronous requests": function () {
var xhr = new sinon.FakeXMLHttpRequest();
xhr.open("GET", "/", false);
sinon.spy(xhr, "respond");
assert(xhr.respond.called);
},
xhr.send();
"should not respond to async requests": function () {
var xhr = new sinon.FakeXMLHttpRequest();
xhr.open("GET", "/", true);
sinon.spy(xhr, "respond");
assert(xhr.respond.called);
},
xhr.send();
"does not respond to async requests": function () {
var xhr = new sinon.FakeXMLHttpRequest();
xhr.open("GET", "/", true);
sinon.spy(xhr, "respond");
assertFalse(xhr.respond.called);
}
});
xhr.send();
testCase("ServerRespondWithTest", {
setUp: function () {
this.server = sinon.fakeServer.create();
assert.isFalse(xhr.respond.called);
}
},
this.getRootAsync = new sinon.FakeXMLHttpRequest();
this.getRootAsync.open("GET", "/", true);
this.getRootAsync.send();
sinon.spy(this.getRootAsync, "respond");
"respondWith": {
setUp: function () {
this.server = sinon.fakeServer.create();
this.postRootAsync = new sinon.FakeXMLHttpRequest();
this.postRootAsync.open("POST", "/", true);
this.postRootAsync.send();
sinon.spy(this.postRootAsync, "respond");
this.getRootAsync = new sinon.FakeXMLHttpRequest();
this.getRootAsync.open("GET", "/", true);
this.getRootAsync.send();
sinon.spy(this.getRootAsync, "respond");
this.getRootSync = new sinon.FakeXMLHttpRequest();
this.getRootSync.open("GET", "/", false);
this.postRootAsync = new sinon.FakeXMLHttpRequest();
this.postRootAsync.open("POST", "/", true);
this.postRootAsync.send();
sinon.spy(this.postRootAsync, "respond");
this.getPathAsync = new sinon.FakeXMLHttpRequest();
this.getPathAsync.open("GET", "/path", true);
this.getPathAsync.send();
sinon.spy(this.getPathAsync, "respond");
this.getRootSync = new sinon.FakeXMLHttpRequest();
this.getRootSync.open("GET", "/", false);
this.postPathAsync = new sinon.FakeXMLHttpRequest();
this.postPathAsync.open("POST", "/path", true);
this.postPathAsync.send();
sinon.spy(this.postPathAsync, "respond");
},
this.getPathAsync = new sinon.FakeXMLHttpRequest();
this.getPathAsync.open("GET", "/path", true);
this.getPathAsync.send();
sinon.spy(this.getPathAsync, "respond");
tearDown: function () {
this.server.restore();
},
this.postPathAsync = new sinon.FakeXMLHttpRequest();
this.postPathAsync.open("POST", "/path", true);
this.postPathAsync.send();
sinon.spy(this.postPathAsync, "respond");
},
"should respond to queued async requests": function () {
this.server.respondWith("Oh yeah! Duffman!");
tearDown: function () {
this.server.restore();
},
this.server.respond();
"responds to queued async requests": function () {
this.server.respondWith("Oh yeah! Duffman!");
assert(this.getRootAsync.respond.called);
assertEquals([200, {}, "Oh yeah! Duffman!"], this.getRootAsync.respond.args[0]);
},
this.server.respond();
"should respond to all queued async requests": function () {
this.server.respondWith("Oh yeah! Duffman!");
assert(this.getRootAsync.respond.called);
assert.equals(this.getRootAsync.respond.args[0], [200, {}, "Oh yeah! Duffman!"]);
},
this.server.respond();
"responds to all queued async requests": function () {
this.server.respondWith("Oh yeah! Duffman!");
assert(this.getRootAsync.respond.called);
assert(this.getPathAsync.respond.called);
},
this.server.respond();
"should respond with status, headers, and body": function () {
var headers = { "Content-Type": "X-test" };
this.server.respondWith([201, headers, "Oh yeah!"]);
assert(this.getRootAsync.respond.called);
assert(this.getPathAsync.respond.called);
},
this.server.respond();
"responds with status, headers, and body": function () {
var headers = { "Content-Type": "X-test" };
this.server.respondWith([201, headers, "Oh yeah!"]);
assertEquals([201, headers, "Oh yeah!"], this.getRootAsync.respond.args[0]);
},
this.server.respond();
"should handle responding with empty queue": function () {
delete this.server.queue;
var server = this.server;
assert.equals(this.getRootAsync.respond.args[0], [201, headers, "Oh yeah!"]);
},
assertNoException(function () {
server.respond();
});
},
"handles responding with empty queue": function () {
delete this.server.queue;
var server = this.server;
"should respond to sync request with canned answers": function () {
this.server.respondWith([210, { "X-Ops": "Yeah" }, "Body, man"]);
refute.exception(function () {
server.respond();
});
},
this.getRootSync.send();
"responds to sync request with canned answers": function () {
this.server.respondWith([210, { "X-Ops": "Yeah" }, "Body, man"]);
assertEquals(210, this.getRootSync.status);
assertEquals("X-Ops: Yeah\r\n", this.getRootSync.getAllResponseHeaders());
assertEquals("Body, man", this.getRootSync.responseText);
},
this.getRootSync.send();
"should respond to sync request with 404 if no response is set": function () {
this.getRootSync.send();
assert.equals(this.getRootSync.status, 210);
assert.equals(this.getRootSync.getAllResponseHeaders(), "X-Ops: Yeah\r\n");
assert.equals(this.getRootSync.responseText, "Body, man");
},
assertEquals(404, this.getRootSync.status);
assertEquals("", this.getRootSync.getAllResponseHeaders());
assertEquals("", this.getRootSync.responseText);
},
"responds to sync request with 404 if no response is set": function () {
this.getRootSync.send();
"should respond to async request with 404 if no response is set": function () {
this.server.respond();
assert.equals(this.getRootSync.status, 404);
assert.equals(this.getRootSync.getAllResponseHeaders(), "");
assert.equals(this.getRootSync.responseText, "");
},
assertEquals([404, {}, ""], this.getRootAsync.respond.args[0]);
},
"responds to async request with 404 if no response is set": function () {
this.server.respond();
"should respond to specific URL": function () {
this.server.respondWith("/path", "Duffman likes Duff beer");
assert.equals(this.getRootAsync.respond.args[0], [404, {}, ""]);
},
this.server.respond();
"responds to specific URL": function () {
this.server.respondWith("/path", "Duffman likes Duff beer");
assertEquals([404, {}, ""], this.getRootAsync.respond.args[0]);
assertEquals([200, {}, "Duffman likes Duff beer"], this.getPathAsync.respond.args[0]);
},
this.server.respond();
"should respond to URL matched by regexp": function () {
this.server.respondWith(/^\/p.*/, "Regexp");
assert.equals(this.getRootAsync.respond.args[0], [404, {}, ""]);
assert.equals(this.getPathAsync.respond.args[0], [200, {}, "Duffman likes Duff beer"]);
},
this.server.respond();
"responds to URL matched by regexp": function () {
this.server.respondWith(/^\/p.*/, "Regexp");
assertEquals([200, {}, "Regexp"], this.getPathAsync.respond.args[0]);
},
this.server.respond();
"should not respond to URL not matched by regexp": function () {
this.server.respondWith(/^\/p.*/, "No regexp match");
assert.equals(this.getPathAsync.respond.args[0], [200, {}, "Regexp"]);
},
this.server.respond();
"does not respond to URL not matched by regexp": function () {
this.server.respondWith(/^\/p.*/, "No regexp match");
assertEquals([404, {}, ""], this.getRootAsync.respond.args[0]);
},
this.server.respond();
"should respond to all URLs matched by regexp": function () {
this.server.respondWith(/^\/.*/, "Match all URLs");
assert.equals(this.getRootAsync.respond.args[0], [404, {}, ""]);
},
this.server.respond();
"responds to all URLs matched by regexp": function () {
this.server.respondWith(/^\/.*/, "Match all URLs");
assertEquals([200, {}, "Match all URLs"], this.getRootAsync.respond.args[0]);
assertEquals([200, {}, "Match all URLs"], this.getPathAsync.respond.args[0]);
},
this.server.respond();
"should respond to all requests when match URL is falsy": function () {
this.server.respondWith("", "Falsy URL");
assert.equals(this.getRootAsync.respond.args[0], [200, {}, "Match all URLs"]);
assert.equals(this.getPathAsync.respond.args[0], [200, {}, "Match all URLs"]);
},
this.server.respond();
"responds to all requests when match URL is falsy": function () {
this.server.respondWith("", "Falsy URL");
assertEquals([200, {}, "Falsy URL"], this.getRootAsync.respond.args[0]);
assertEquals([200, {}, "Falsy URL"], this.getPathAsync.respond.args[0]);
},
this.server.respond();
"should respond to all GET requests": function () {
this.server.respondWith("GET", "", "All GETs");
assert.equals(this.getRootAsync.respond.args[0], [200, {}, "Falsy URL"]);
assert.equals(this.getPathAsync.respond.args[0], [200, {}, "Falsy URL"]);
},
this.server.respond();
"responds to all GET requests": function () {
this.server.respondWith("GET", "", "All GETs");
assertEquals([200, {}, "All GETs"], this.getRootAsync.respond.args[0]);
assertEquals([200, {}, "All GETs"], this.getPathAsync.respond.args[0]);
assertEquals([404, {}, ""], this.postRootAsync.respond.args[0]);
assertEquals([404, {}, ""], this.postPathAsync.respond.args[0]);
},
this.server.respond();
"should respond to all 'get' requests (case-insensitivity)": function () {
this.server.respondWith("get", "", "All GETs");
assert.equals(this.getRootAsync.respond.args[0], [200, {}, "All GETs"]);
assert.equals(this.getPathAsync.respond.args[0], [200, {}, "All GETs"]);
assert.equals(this.postRootAsync.respond.args[0], [404, {}, ""]);
assert.equals(this.postPathAsync.respond.args[0], [404, {}, ""]);
},
this.server.respond();
"responds to all 'get' requests (case-insensitivity)": function () {
this.server.respondWith("get", "", "All GETs");
assertEquals([200, {}, "All GETs"], this.getRootAsync.respond.args[0]);
assertEquals([200, {}, "All GETs"], this.getPathAsync.respond.args[0]);
assertEquals([404, {}, ""], this.postRootAsync.respond.args[0]);
assertEquals([404, {}, ""], this.postPathAsync.respond.args[0]);
},
this.server.respond();
"should respond to all PUT requests": function () {
this.server.respondWith("PUT", "", "All PUTs");
assert.equals(this.getRootAsync.respond.args[0], [200, {}, "All GETs"]);
assert.equals(this.getPathAsync.respond.args[0], [200, {}, "All GETs"]);
assert.equals(this.postRootAsync.respond.args[0], [404, {}, ""]);
assert.equals(this.postPathAsync.respond.args[0], [404, {}, ""]);
},
this.server.respond();
"responds to all PUT requests": function () {
this.server.respondWith("PUT", "", "All PUTs");
assertEquals([404, {}, ""], this.getRootAsync.respond.args[0]);
assertEquals([404, {}, ""], this.getPathAsync.respond.args[0]);
assertEquals([404, {}, ""], this.postRootAsync.respond.args[0]);
assertEquals([404, {}, ""], this.postPathAsync.respond.args[0]);
},
this.server.respond();
"should respond to all POST requests": function () {
this.server.respondWith("POST", "", "All POSTs");
assert.equals(this.getRootAsync.respond.args[0], [404, {}, ""]);
assert.equals(this.getPathAsync.respond.args[0], [404, {}, ""]);
assert.equals(this.postRootAsync.respond.args[0], [404, {}, ""]);
assert.equals(this.postPathAsync.respond.args[0], [404, {}, ""]);
},
this.server.respond();
"responds to all POST requests": function () {
this.server.respondWith("POST", "", "All POSTs");
assertEquals([404, {}, ""], this.getRootAsync.respond.args[0]);
assertEquals([404, {}, ""], this.getPathAsync.respond.args[0]);
assertEquals([200, {}, "All POSTs"], this.postRootAsync.respond.args[0]);
assertEquals([200, {}, "All POSTs"], this.postPathAsync.respond.args[0]);
},
this.server.respond();
"should respond to all POST requests to /path": function () {
this.server.respondWith("POST", "/path", "All POSTs");
assert.equals(this.getRootAsync.respond.args[0], [404, {}, ""]);
assert.equals(this.getPathAsync.respond.args[0], [404, {}, ""]);
assert.equals(this.postRootAsync.respond.args[0], [200, {}, "All POSTs"]);
assert.equals(this.postPathAsync.respond.args[0], [200, {}, "All POSTs"]);
},
this.server.respond();
"responds to all POST requests to /path": function () {
this.server.respondWith("POST", "/path", "All POSTs");
assertEquals([404, {}, ""], this.getRootAsync.respond.args[0]);
assertEquals([404, {}, ""], this.getPathAsync.respond.args[0]);
assertEquals([404, {}, ""], this.postRootAsync.respond.args[0]);
assertEquals([200, {}, "All POSTs"], this.postPathAsync.respond.args[0]);
},
this.server.respond();
"should respond to all POST requests matching regexp": function () {
this.server.respondWith("POST", /^\/path(\?.*)?/, "All POSTs");
assert.equals(this.getRootAsync.respond.args[0], [404, {}, ""]);
assert.equals(this.getPathAsync.respond.args[0], [404, {}, ""]);
assert.equals(this.postRootAsync.respond.args[0], [404, {}, ""]);
assert.equals(this.postPathAsync.respond.args[0], [200, {}, "All POSTs"]);
},
this.server.respond();
"responds to all POST requests matching regexp": function () {
this.server.respondWith("POST", /^\/path(\?.*)?/, "All POSTs");
assertEquals([404, {}, ""], this.getRootAsync.respond.args[0]);
assertEquals([404, {}, ""], this.getPathAsync.respond.args[0]);
assertEquals([404, {}, ""], this.postRootAsync.respond.args[0]);
assertEquals([200, {}, "All POSTs"], this.postPathAsync.respond.args[0]);
},
this.server.respond();
"should not respond to aborted requests": function () {
this.server.respondWith("/", "That's my homepage!");
this.getRootAsync.aborted = true;
assert.equals(this.getRootAsync.respond.args[0], [404, {}, ""]);
assert.equals(this.getPathAsync.respond.args[0], [404, {}, ""]);
assert.equals(this.postRootAsync.respond.args[0], [404, {}, ""]);
assert.equals(this.postPathAsync.respond.args[0], [200, {}, "All POSTs"]);
},
this.server.respond();
"does not respond to aborted requests": function () {
this.server.respondWith("/", "That's my homepage!");
this.getRootAsync.aborted = true;
assertFalse(this.getRootAsync.respond.called);
},
this.server.respond();
"should reset requests": function () {
this.server.respondWith("/", "That's my homepage!");
assert.isFalse(this.getRootAsync.respond.called);
},
this.server.respond();
"resets requests": function () {
this.server.respondWith("/", "That's my homepage!");
assertEquals([], this.server.queue);
},
this.server.respond();
"should notify all requests when some throw": function () {
this.getRootAsync.respond = function () {
throw new Error("Oops!");
};
assert.equals(this.server.queue, []);
},
this.server.respondWith("");
this.server.respond();
"notifies all requests when some throw": function () {
this.getRootAsync.respond = function () {
throw new Error("Oops!");
};
assertEquals([200, {}, ""], this.getPathAsync.respond.args[0]);
assertEquals([200, {}, ""], this.postRootAsync.respond.args[0]);
assertEquals([200, {}, ""], this.postPathAsync.respond.args[0]);
},
this.server.respondWith("");
this.server.respond();
"should recognize request with hostname": function () {
this.server.respondWith("/", [200, {}, "Yep"]);
var xhr = new sinon.FakeXMLHttpRequest();
var loc = window.location;
xhr.open("GET", loc.protocol + "//" + loc.host + "/", true);
xhr.send();
sinon.spy(xhr, "respond");
assert.equals(this.getPathAsync.respond.args[0], [200, {}, ""]);
assert.equals(this.postRootAsync.respond.args[0], [200, {}, ""]);
assert.equals(this.postPathAsync.respond.args[0], [200, {}, ""]);
},
this.server.respond();
"recognizes request with hostname": function () {
this.server.respondWith("/", [200, {}, "Yep"]);
var xhr = new sinon.FakeXMLHttpRequest();
var loc = window.location;
xhr.open("GET", loc.protocol + "//" + loc.host + "/", true);
xhr.send();
sinon.spy(xhr, "respond");
assertEquals([200, {}, "Yep"], xhr.respond.args[0]);
},
this.server.respond();
"should throw understandable error if response is not a string": function () {
var error;
assert.equals(xhr.respond.args[0], [200, {}, "Yep"]);
},
try {
this.server.respondWith("/", {});
} catch (e) {
error = e;
}
"throws understandable error if response is not a string": function () {
var error;
assertObject(error);
assertEquals("Fake server response body should be string, but was object", error.message);
},
try {
this.server.respondWith("/", {});
} catch (e) {
error = e;
}
"should throw understandable error if response in array is not a string": function () {
var error;
assert.isObject(error);
assert.equals(error.message, "Fake server response body should be string, but was object");
},
try {
this.server.respondWith("/", [200, {}]);
} catch (e) {
error = e;
}
"throws understandable error if response in array is not a string": function () {
var error;
assertObject(error);
assertEquals("Fake server response body should be string, but was undefined",
error.message);
},
try {
this.server.respondWith("/", [200, {}]);
} catch (e) {
error = e;
}
"should be able to pass the same args to respond directly": function() {
this.server.respond("Oh yeah! Duffman!");
assert.isObject(error);
assert.equals( error.message, "Fake server response body should be string, but was undefined");
},
assertEquals([200, {}, "Oh yeah! Duffman!"], this.getRootAsync.respond.args[0]);
assertEquals([200, {}, "Oh yeah! Duffman!"], this.getPathAsync.respond.args[0]);
assertEquals([200, {}, "Oh yeah! Duffman!"], this.postRootAsync.respond.args[0]);
assertEquals([200, {}, "Oh yeah! Duffman!"], this.postPathAsync.respond.args[0]);
}
});
"is able to pass the same args to respond directly": function() {
this.server.respond("Oh yeah! Duffman!");
testCase("ServerRespondWithFunctionHandlerTest", {
setUp: function () {
this.server = sinon.fakeServer.create();
assert.equals(this.getRootAsync.respond.args[0], [200, {}, "Oh yeah! Duffman!"]);
assert.equals(this.getPathAsync.respond.args[0], [200, {}, "Oh yeah! Duffman!"]);
assert.equals(this.postRootAsync.respond.args[0], [200, {}, "Oh yeah! Duffman!"]);
assert.equals(this.postPathAsync.respond.args[0], [200, {}, "Oh yeah! Duffman!"]);
}
},
tearDown: function () {
this.server.restore();
},
"respondWithFunctionHandler": {
setUp: function () {
this.server = sinon.fakeServer.create();
},
"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();
tearDown: function () {
this.server.restore();
},
this.server.respond();
"yields 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();
assert(handler.calledOnce);
assert(handler.calledWith(xhr));
},
this.server.respond();
"should respond to request from function handler": function () {
this.server.respondWith("/hello", function (xhr) {
xhr.respond(200, { "Content-Type": "application/json" }, '{"id":42}');
});
assert(handler.calledOnce);
assert(handler.calledWith(xhr));
},
var request = new sinon.FakeXMLHttpRequest();
request.open("GET", "/hello");
request.send();
"responds to request from function handler": function () {
this.server.respondWith("/hello", function (xhr) {
xhr.respond(200, { "Content-Type": "application/json" }, '{"id":42}');
});
this.server.respond();
var request = new sinon.FakeXMLHttpRequest();
request.open("GET", "/hello");
request.send();
assertEquals(200, request.status);
assertEquals({ "Content-Type": "application/json" }, request.responseHeaders);
assertEquals('{"id":42}', request.responseText);
},
this.server.respond();
"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();
assert.equals(request.status, 200);
assert.equals(request.responseHeaders, { "Content-Type": "application/json" });
assert.equals(request.responseText, '{"id":42}');
},
this.server.respond();
"yields 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();
assert(handler.calledOnce);
},
this.server.respond();
"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();
assert(handler.calledOnce);
},
this.server.respond();
"does 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();
assert(!handler.called);
},
this.server.respond();
"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();
assert(!handler.called);
},
this.server.respond();
"yields 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();
assert(handler.calledOnce);
},
this.server.respond();
"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();
assert(handler.calledOnce);
},
this.server.respond();
"does 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();
assert(!handler.called);
},
this.server.respond();
"should add function handler without method or url filter": function () {
this.server.respondWith(function (xhr) {
xhr.respond(200, { "Content-Type": "application/json" }, '{"id":42}');
});
assert(!handler.called);
},
var request = new sinon.FakeXMLHttpRequest();
request.open("GET", "/whatever");
request.send();
"adds function handler without method or url filter": function () {
this.server.respondWith(function (xhr) {
xhr.respond(200, { "Content-Type": "application/json" }, '{"id":42}');
});
this.server.respond();
var request = new sinon.FakeXMLHttpRequest();
request.open("GET", "/whatever");
request.send();
assertEquals(200, request.status);
assertEquals({ "Content-Type": "application/json" }, request.responseHeaders);
assertEquals('{"id":42}', request.responseText);
},
this.server.respond();
"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();
assert.equals(request.status, 200);
assert.equals(request.responseHeaders, { "Content-Type": "application/json" });
assert.equals(request.responseText, '{"id":42}');
},
this.server.respond();
"does 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();
assert(handler.called);
assert(xhr.respond.calledOnce);
},
this.server.respond();
"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();
assert(handler.called);
assert(xhr.respond.calledOnce);
},
this.server.respond();
"yields 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();
assert(handler.called);
assertEquals([xhr, 3], handler.args[0]);
}
});
this.server.respond();
testCase("ServerRespondFakeHTTPVerbTest", {
setUp: function () {
this.server = sinon.fakeServer.create();
this.request = new sinon.FakeXMLHttpRequest();
this.request.open("post", "/path", true);
this.request.send("_method=delete");
sinon.spy(this.request, "respond");
assert(handler.called);
assert.equals(handler.args[0], [xhr, 3]);
}
},
tearDown: function () {
this.server.restore();
},
"respondFakeHTTPVerb": {
setUp: function () {
this.server = sinon.fakeServer.create();
"should not respond to DELETE request with _method parameter": function () {
this.server.respondWith("DELETE", "", "");
this.request = new sinon.FakeXMLHttpRequest();
this.request.open("post", "/path", true);
this.request.send("_method=delete");
sinon.spy(this.request, "respond");
},
this.server.respond();
tearDown: function () {
this.server.restore();
},
assertEquals([404, {}, ""], this.request.respond.args[0]);
},
"does not respond to DELETE request with _method parameter": function () {
this.server.respondWith("DELETE", "", "");
"should respond to 'fake' DELETE request": function () {
this.server.fakeHTTPMethods = true;
this.server.respondWith("DELETE", "", "OK");
this.server.respond();
this.server.respond();
assert.equals(this.request.respond.args[0], [404, {}, ""]);
},
assertEquals([200, {}, "OK"], this.request.respond.args[0]);
},
"responds to 'fake' DELETE request": function () {
this.server.fakeHTTPMethods = true;
this.server.respondWith("DELETE", "", "OK");
"should not respond to POST when faking DELETE": function () {
this.server.fakeHTTPMethods = true;
this.server.respondWith("POST", "", "OK");
this.server.respond();
this.server.respond();
assert.equals(this.request.respond.args[0], [200, {}, "OK"]);
},
assertEquals([404, {}, ""], this.request.respond.args[0]);
},
"does not respond to POST when faking DELETE": function () {
this.server.fakeHTTPMethods = true;
this.server.respondWith("POST", "", "OK");
"should not fake method when not POSTing": function () {
this.server.fakeHTTPMethods = true;
this.server.respondWith("DELETE", "", "OK");
this.server.respond();
var request = new sinon.FakeXMLHttpRequest();
request.open("GET", "/");
request.send();
request.respond = sinon.spy();
this.server.respond();
assert.equals(this.request.respond.args[0], [404, {}, ""]);
},
assertEquals([404, {}, ""], request.respond.args[0]);
},
"does not fake method when not POSTing": function () {
this.server.fakeHTTPMethods = true;
this.server.respondWith("DELETE", "", "OK");
"should customize HTTP method extraction": function () {
this.server.getHTTPMethod = function (request) {
return "PUT";
};
var request = new sinon.FakeXMLHttpRequest();
request.open("GET", "/");
request.send();
request.respond = sinon.spy();
this.server.respond();
this.server.respondWith("PUT", "", "OK");
assert.equals(request.respond.args[0], [404, {}, ""]);
},
this.server.respond();
"customizes HTTP method extraction": function () {
this.server.getHTTPMethod = function (request) {
return "PUT";
};
assertEquals([200, {}, "OK"], this.request.respond.args[0]);
},
this.server.respondWith("PUT", "", "OK");
"should not fail when getting the HTTP method from a request with no body":
function () {
var server = this.server;
server.fakeHTTPMethods = true;
this.server.respond();
assertEquals("POST", server.getHTTPMethod({ method: "POST" }));
}
});
assert.equals(this.request.respond.args[0], [200, {}, "OK"]);
},
(function () {
function get(url) {
var request = new sinon.FakeXMLHttpRequest();
sinon.spy(request, "respond");
request.open("get", "/path", true);
request.send();
"does not fail when getting the HTTP method from a request with no body":
function () {
var server = this.server;
server.fakeHTTPMethods = true;
return request;
}
assert.equals(server.getHTTPMethod({ method: "POST" }), "POST");
}
},
testCase("ServerAutoResponseTest", {
"autoResponse": {
setUp: function () {
this.get = function get(url) {
var request = new sinon.FakeXMLHttpRequest();
sinon.spy(request, "respond");
request.open("get", "/path", true);
request.send();
return request;
};
this.server = sinon.fakeServer.create();

@@ -644,53 +620,53 @@ this.clock = sinon.useFakeTimers();

"should respond async automatically after 10ms": function () {
"responds async automatically after 10ms": function () {
this.server.autoRespond = true;
var request = get("/path");
var request = this.get("/path");
this.clock.tick(10);
assertTrue(request.respond.calledOnce);
assert.isTrue(request.respond.calledOnce);
},
"normal server should not respond automatically": function () {
var request = get("/path");
"normal server does not respond automatically": function () {
var request = this.get("/path");
this.clock.tick(100);
assertTrue(!request.respond.called);
assert.isTrue(!request.respond.called);
},
"should only auto-respond once": function () {
"auto-responds only once": function () {
this.server.autoRespond = true;
var requests = [get("/path")];
var requests = [this.get("/path")];
this.clock.tick(5);
requests.push(get("/other"));
requests.push(this.get("/other"));
this.clock.tick(5);
assertTrue(requests[0].respond.calledOnce);
assertTrue(requests[1].respond.calledOnce);
assert.isTrue(requests[0].respond.calledOnce);
assert.isTrue(requests[1].respond.calledOnce);
},
"should auto-respond after having already responded": function () {
"auto-responds after having already responded": function () {
this.server.autoRespond = true;
var requests = [get("/path")];
var requests = [this.get("/path")];
this.clock.tick(10);
requests.push(get("/other"));
requests.push(this.get("/other"));
this.clock.tick(10);
assertTrue(requests[0].respond.calledOnce);
assertTrue(requests[1].respond.calledOnce);
assert.isTrue(requests[0].respond.calledOnce);
assert.isTrue(requests[1].respond.calledOnce);
},
"should set auto-respond timeout to 50ms": function () {
"sets auto-respond timeout to 50ms": function () {
this.server.autoRespond = true;
this.server.autoRespondAfter = 50;
var request = get("/path");
var request = this.get("/path");
this.clock.tick(49);
assertFalse(request.respond.called);
assert.isFalse(request.respond.called);
this.clock.tick(1);
assertTrue(request.respond.calledOnce);
assert.isTrue(request.respond.calledOnce);
}
});
}());
}
});
/*jslint onevar: false, browser: false, regexp: false, browser: true*/
/*globals testCase
sinon
assert
assertSame
assertNotSame
assertEquals
assertTrue
assertFalse
assertNull
assertException
assertNoException
assertUndefined
assertObject
assertFunction*/
/*globals sinon buster*/
/**

@@ -20,7 +7,7 @@ * @author Christian Johansen (christian@cjohansen.no)

*
* Copyright (c) 2010-2011 Christian Johansen
* Copyright (c) 2010-2012 Christian Johansen
*/
"use strict";
testCase("ServerWithClockTest", {
buster.testCase("sinon.fakeServerWithClock", {
setUp: function () {

@@ -32,9 +19,6 @@ this.server = sinon.fakeServerWithClock.create();

this.server.restore();
if (this.clock) {
this.clock.restore();
}
if (this.clock) { this.clock.restore(); }
},
"should call 'super' when adding requests": sinon.test(function () {
"calls 'super' when adding requests": sinon.test(function () {
var addRequest = this.stub(sinon.fakeServer, "addRequest");

@@ -48,10 +32,10 @@ var xhr = {};

"should set reference to clock when adding async request": function () {
"sets reference to clock when adding async request": function () {
this.server.addRequest({ async: true });
assertObject(this.server.clock);
assertFunction(this.server.clock.tick);
assert.isObject(this.server.clock);
assert.isFunction(this.server.clock.tick);
},
"should set longest timeout from setTimeout": function () {
"sets longest timeout from setTimeout": function () {
this.server.addRequest({ async: true });

@@ -64,6 +48,6 @@

assertEquals(29, this.server.longestTimeout);
assert.equals(this.server.longestTimeout, 29);
},
"should set longest timeout from setInterval": function () {
"sets longest timeout from setInterval": function () {
this.server.addRequest({ async: true });

@@ -76,6 +60,6 @@

assertEquals(132, this.server.longestTimeout);
assert.equals(this.server.longestTimeout, 132);
},
"should reset clock": function () {
"resets clock": function () {
this.server.addRequest({ async: true });

@@ -85,6 +69,6 @@

assertSame(sinon.timers.setTimeout, setTimeout);
assert.same(setTimeout, sinon.timers.setTimeout);
},
"should not reset clock second time": function () {
"does not reset clock second time": function () {
this.server.addRequest({ async: true });

@@ -96,144 +80,144 @@ this.server.respond("");

assertNotSame(sinon.timers.setTimeout, setTimeout);
}
});
testCase("ServerWithClockExistingClockTest", {
setUp: function () {
this.clock = sinon.useFakeTimers();
this.server = sinon.fakeServerWithClock.create();
refute.same(setTimeout, sinon.timers.setTimeout);
},
tearDown: function () {
this.clock.restore();
this.server.restore();
},
"existing clock": {
setUp: function () {
this.clock = sinon.useFakeTimers();
this.server = sinon.fakeServerWithClock.create();
},
"should use existing clock": function () {
this.server.addRequest({ async: true });
tearDown: function () {
this.clock.restore();
this.server.restore();
},
assertSame(this.clock, this.server.clock);
},
"uses existing clock": function () {
this.server.addRequest({ async: true });
"should record longest timeout using setTimeout and existing clock": function () {
this.server.addRequest({ async: true });
assert.same(this.server.clock, this.clock);
},
setInterval(function () {}, 42);
setTimeout(function () {}, 23);
setTimeout(function () {}, 53);
setInterval(function () {}, 12);
"records longest timeout using setTimeout and existing clock": function () {
this.server.addRequest({ async: true });
assertSame(53, this.server.longestTimeout);
},
setInterval(function () {}, 42);
setTimeout(function () {}, 23);
setTimeout(function () {}, 53);
setInterval(function () {}, 12);
"should record longest timeout using setInterval and existing clock": function () {
this.server.addRequest({ async: true });
assert.same(this.server.longestTimeout, 53);
},
setInterval(function () {}, 92);
setTimeout(function () {}, 73);
setTimeout(function () {}, 53);
setInterval(function () {}, 12);
"records longest timeout using setInterval and existing clock": function () {
this.server.addRequest({ async: true });
assertSame(92, this.server.longestTimeout);
},
setInterval(function () {}, 92);
setTimeout(function () {}, 73);
setTimeout(function () {}, 53);
setInterval(function () {}, 12);
"should not reset clock": function () {
this.server.respond("");
assert.same(this.server.longestTimeout, 92);
},
assertSame(this.clock, setTimeout.clock);
}
});
"does not reset clock": function () {
this.server.respond("");
testCase("ServerWithClockRespondTest", {
setUp: function () {
this.server = sinon.fakeServerWithClock.create();
this.server.addRequest({ async: true });
assert.same(setTimeout.clock, this.clock);
}
},
tearDown: function () {
this.server.restore();
},
"respond": {
setUp: function () {
this.server = sinon.fakeServerWithClock.create();
this.server.addRequest({ async: true });
},
"should tick the clock to fire the longest timeout": function () {
this.server.longestTimeout = 96;
tearDown: function () {
this.server.restore();
},
this.server.respond();
"ticks the clock to fire the longest timeout": function () {
this.server.longestTimeout = 96;
assertEquals(96, this.server.clock.now);
},
this.server.respond();
"should tick the clock to fire the longest timeout when multiple responds": function () {
setInterval(function () {}, 13);
this.server.respond();
var xhr = new sinon.FakeXMLHttpRequest();
setInterval(function () {}, 17);
this.server.respond();
assert.equals(this.server.clock.now, 96);
},
assertEquals(17, this.server.clock.now);
},
"ticks the clock to fire the longest timeout when multiple responds": function () {
setInterval(function () {}, 13);
this.server.respond();
var xhr = new sinon.FakeXMLHttpRequest();
setInterval(function () {}, 17);
this.server.respond();
"should reset longest timeout": function () {
this.server.longestTimeout = 96;
assert.equals(this.server.clock.now, 17);
},
this.server.respond();
"resets longest timeout": function () {
this.server.longestTimeout = 96;
assertEquals(0, this.server.longestTimeout);
},
this.server.respond();
"should call original respond": sinon.test(function () {
var obj = {};
var respond = this.stub(sinon.fakeServer, "respond").returns(obj);
assert.equals(this.server.longestTimeout, 0);
},
var result = this.server.respond("GET", "/", "");
"calls original respond": sinon.test(function () {
var obj = {};
var respond = this.stub(sinon.fakeServer, "respond").returns(obj);
assertEquals(obj, result);
assert(respond.calledWith("GET", "/", ""));
assert(respond.calledOn(this.server));
})
});
var result = this.server.respond("GET", "/", "");
testCase("ServerJQueryCompatMode", {
setUp: function () {
this.server = sinon.fakeServerWithClock.create();
this.request = new sinon.FakeXMLHttpRequest();
this.request.open("get", "/", true);
this.request.send();
sinon.spy(this.request, "respond");
assert.equals(result, obj);
assert(respond.calledWith("GET", "/", ""));
assert(respond.calledOn(this.server));
})
},
tearDown: function () {
this.server.restore();
},
"jQuery compat mode": {
setUp: function () {
this.server = sinon.fakeServerWithClock.create();
"should handle clock automatically": function () {
this.server.respondWith("OK");
var spy = sinon.spy();
this.request = new sinon.FakeXMLHttpRequest();
this.request.open("get", "/", true);
this.request.send();
sinon.spy(this.request, "respond");
},
setTimeout(spy, 13);
this.server.respond();
this.server.restore();
tearDown: function () {
this.server.restore();
},
assert(spy.called);
assertSame(sinon.timers.setTimeout, setTimeout);
},
"handles clock automatically": function () {
this.server.respondWith("OK");
var spy = sinon.spy();
"should finish xhr from setInterval like jQuery 1.3.x does": function () {
this.server.respondWith("Hello World");
var xhr = new sinon.FakeXMLHttpRequest();
xhr.open("GET", "/");
xhr.send();
setTimeout(spy, 13);
this.server.respond();
this.server.restore();
var spy = sinon.spy();
assert(spy.called);
assert.same(setTimeout, sinon.timers.setTimeout);
},
setInterval(function () {
spy(xhr.responseText, xhr.statusText, xhr);
}, 13);
"finishes xhr from setInterval like jQuery 1.3.x does": function () {
this.server.respondWith("Hello World");
var xhr = new sinon.FakeXMLHttpRequest();
xhr.open("GET", "/");
xhr.send();
this.server.respond();
var spy = sinon.spy();
assertEquals("Hello World", spy.args[0][0]);
assertEquals("OK", spy.args[0][1]);
assertEquals(200, spy.args[0][2].status);
setInterval(function () {
spy(xhr.responseText, xhr.statusText, xhr);
}, 13);
this.server.respond();
assert.equals(spy.args[0][0], "Hello World");
assert.equals(spy.args[0][1], "OK");
assert.equals(spy.args[0][2].status, 200);
}
}
});
/*jslint onevar: false, eqeqeq: false, plusplus: false*/
/*globals testCase
sinon
called
jstestdriver
assert
assertFalse
assertEquals
assertNotEquals
assertNumber
assertException
assertSame
assertNotSame
assertUndefined
assertObject
assertFunction
setTimeout
setInterval
clearTimeout
clearInterval*/
/*globals sinon buster setTimeout setInterval clearTimeout clearInterval*/
/**

@@ -25,8 +7,8 @@ * @author Christian Johansen (christian@cjohansen.no)

*
* Copyright (c) 2010-2011 Christian Johansen
* Copyright (c) 2010-2012 Christian Johansen
*/
"use strict";
if (typeof require == "function" && typeof testCase == "undefined") {
var testCase = require("../../test_case_shim");
if (typeof require == "function" && typeof module == "object") {
var buster = require("../../runner");
var sinon = require("../../../lib/sinon");

@@ -36,4 +18,8 @@ sinon.extend(sinon, require("../../../lib/sinon/util/fake_timers"));

(function (global) {
testCase("SetTimeOutTest", {
buster.testCase("sinon.clock", {
setUp: function () {
this.global = typeof global != "undefined" ? global : window;
},
"setTimeout": {
setUp: function () {

@@ -48,28 +34,22 @@ this.clock = sinon.clock.create();

"should be function": function () {
assertFunction(this.clock.setTimeout);
},
"should throw if no arguments": function () {
"throws if no arguments": function () {
var clock = this.clock;
assertException(function () {
clock.setTimeout();
});
assert.exception(function () { clock.setTimeout(); });
},
"should return numeric id": function () {
"returns numeric id": function () {
var result = this.clock.setTimeout("");
assertNumber(result);
assert.isNumber(result);
},
"should return unique id": function () {
"returns unique id": function () {
var id1 = this.clock.setTimeout("");
var id2 = this.clock.setTimeout("");
assertNotEquals(id1, id2);
refute.equals(id2, id1);
},
"should set timers on instance": function () {
"sets timers on instance": function () {
var clock1 = sinon.clock.create();

@@ -83,7 +63,7 @@ var clock2 = sinon.clock.create();

assertFalse(stubs[0].called);
assert.isFalse(stubs[0].called);
assert(stubs[1].called);
},
"should eval non-function callbacks": function () {
"evals non-function callbacks": function () {
this.clock.setTimeout("sinon.clock.evalCalled = true", 10);

@@ -93,6 +73,29 @@ this.clock.tick(10);

assert(sinon.clock.evalCalled);
},
"passes setTimeout parameters": function() {
var clock = sinon.clock.create();
var stub = sinon.stub.create();
clock.setTimeout(stub, 2, "the first", "the second");
clock.tick(3);
assert.isTrue(stub.calledWithExactly("the first", "the second"));
},
"calls correct timeout on recursive tick": function() {
var clock = sinon.clock.create();
var stub = sinon.stub.create();
var recurseCallback = function () { clock.tick(100); };
clock.setTimeout(recurseCallback, 50);
clock.setTimeout(stub, 100);
clock.tick(50);
assert(stub.called);
}
});
},
testCase("ClockTickTest", {
"tick": {
setUp: function () {

@@ -106,3 +109,3 @@ this.clock = sinon.useFakeTimers(0);

"should trigger immediately without specified delay": function () {
"triggers immediately without specified delay": function () {
var stub = sinon.stub.create();

@@ -116,3 +119,3 @@ this.clock.setTimeout(stub);

"should not trigger without sufficient delay": function () {
"does not trigger without sufficient delay": function () {
var stub = sinon.stub.create();

@@ -122,6 +125,6 @@ this.clock.setTimeout(stub, 100);

assertFalse(stub.called);
assert.isFalse(stub.called);
},
"should trigger after sufficient delay": function () {
"triggers after sufficient delay": function () {
var stub = sinon.stub.create();

@@ -134,3 +137,3 @@ this.clock.setTimeout(stub, 100);

"should trigger simultaneous timers": function () {
"triggers simultaneous timers": function () {
var spies = [sinon.spy(), sinon.spy()];

@@ -146,3 +149,3 @@ this.clock.setTimeout(spies[0], 100);

"should trigger multiple simultaneous timers": function () {
"triggers multiple simultaneous timers": function () {
var spies = [sinon.spy(), sinon.spy(), sinon.spy(), sinon.spy()];

@@ -162,3 +165,3 @@ this.clock.setTimeout(spies[0], 100);

"should wait after setTimeout was called": function () {
"waits after setTimeout was called": function () {
this.clock.tick(100);

@@ -169,3 +172,3 @@ var stub = sinon.stub.create();

assertFalse(stub.called);
assert.isFalse(stub.called);
this.clock.tick(100);

@@ -181,11 +184,11 @@ assert(stub.called);

this.clock.tick(89);
assertFalse(stubs[0].called);
assertFalse(stubs[1].called);
assert.isFalse(stubs[0].called);
assert.isFalse(stubs[1].called);
this.clock.setTimeout(stubs[2], 20);
this.clock.tick(1);
assert(stubs[0].called);
assertFalse(stubs[1].called);
assertFalse(stubs[2].called);
assert.isFalse(stubs[1].called);
assert.isFalse(stubs[2].called);
this.clock.tick(19);
assertFalse(stubs[1].called);
assert.isFalse(stubs[1].called);
assert(stubs[2].called);

@@ -196,3 +199,3 @@ this.clock.tick(1);

"should trigger even when some throw": function () {
"triggers even when some throw": function () {
var clock = this.clock;

@@ -204,4 +207,4 @@ var stubs = [sinon.stub.create().throws(), sinon.stub.create()];

assertException(function() {
clock.tick(120);
assert.exception(function() {
clock.tick(120);
});

@@ -213,3 +216,3 @@

"should call function with global object or null (strict mode) as this": function () {
"calls function with global object or null (strict mode) as this": function () {
var clock = this.clock;

@@ -219,10 +222,10 @@ var stub = sinon.stub.create().throws();

assertException(function() {
clock.tick(100);
assert.exception(function() {
clock.tick(100);
});
assert(stub.calledOn(global) || stub.calledOn(null));
assert(stub.calledOn(this.global) || stub.calledOn(null));
},
"should trigger in the order scheduled": function () {
"triggers in the order scheduled": function () {
var spies = [sinon.spy.create(), sinon.spy.create()];

@@ -237,3 +240,3 @@ this.clock.setTimeout(spies[0], 13);

"should create updated Date while ticking": function () {
"creates updated Date while ticking": function () {
var spy = sinon.spy.create();

@@ -247,3 +250,3 @@

assertEquals(10, spy.callCount);
assert.equals(spy.callCount, 10);
assert(spy.calledWith(10));

@@ -261,3 +264,3 @@ assert(spy.calledWith(20));

"should fire timer in intervals of 13": function () {
"fires timer in intervals of 13": function () {
var spy = sinon.spy.create();

@@ -268,6 +271,6 @@ this.clock.setInterval(spy, 13);

assertEquals(38, spy.callCount);
assert.equals(spy.callCount, 38);
},
"should fire timers in correct order": function () {
"fires timers in correct order": function () {
var spy13 = sinon.spy.create();

@@ -286,4 +289,4 @@ var spy10 = sinon.spy.create();

assertEquals(38, spy13.callCount);
assertEquals(50, spy10.callCount);
assert.equals(spy13.callCount, 38);
assert.equals(spy10.callCount, 50);

@@ -297,3 +300,3 @@ assert(spy13.calledWith(416));

"should trigger timeouts and intervals in the order scheduled": function () {
"triggers timeouts and intervals in the order scheduled": function () {
var spies = [sinon.spy.create(), sinon.spy.create()];

@@ -306,7 +309,7 @@ this.clock.setInterval(spies[0], 10);

assert(spies[0].calledBefore(spies[1]));
assertEquals(10, spies[0].callCount);
assertEquals(1, spies[1].callCount);
assert.equals(spies[0].callCount, 10);
assert.equals(spies[1].callCount, 1);
},
"should not fire canceled intervals": function () {
"does not fire canceled intervals": function () {
var id;

@@ -322,6 +325,6 @@ var callback = sinon.spy(function () {

assertEquals(3, callback.callCount);
assert.equals(callback.callCount, 3);
},
"should pass 6 seconds": function () {
"passes 6 seconds": function () {
var spy = sinon.spy.create();

@@ -332,6 +335,6 @@ this.clock.setInterval(spy, 4000);

assertEquals(2, spy.callCount);
assert.equals(spy.callCount, 2);
},
"should pass 1 minute": function () {
"passes 1 minute": function () {
var spy = sinon.spy.create();

@@ -342,6 +345,6 @@ this.clock.setInterval(spy, 6000);

assertEquals(10, spy.callCount);
assert.equals(spy.callCount, 10);
},
"should pass 2 hours, 34 minutes and 12 seconds": function () {
"passes 2 hours, 34 minutes and 12 seconds": function () {
var spy = sinon.spy.create();

@@ -352,6 +355,6 @@ this.clock.setInterval(spy, 10000);

assertEquals(925, spy.callCount);
assert.equals(spy.callCount, 925);
},
"should throw for invalid format": function () {
"throws for invalid format": function () {
var spy = sinon.spy.create();

@@ -361,10 +364,10 @@ this.clock.setInterval(spy, 10000);

assertException(function () {
assert.exception(function () {
test.clock.tick("12:02:34:10");
});
assertEquals(0, spy.callCount);
assert.equals(spy.callCount, 0);
},
"should throw for invalid minutes": function () {
"throws for invalid minutes": function () {
var spy = sinon.spy.create();

@@ -374,10 +377,10 @@ this.clock.setInterval(spy, 10000);

assertException(function () {
assert.exception(function () {
test.clock.tick("67:10");
});
assertEquals(0, spy.callCount);
assert.equals(spy.callCount, 0);
},
"should throw for negative minutes": function () {
"throws for negative minutes": function () {
var spy = sinon.spy.create();

@@ -387,16 +390,16 @@ this.clock.setInterval(spy, 10000);

assertException(function () {
assert.exception(function () {
test.clock.tick("-7:10");
});
assertEquals(0, spy.callCount);
assert.equals(spy.callCount, 0);
},
"should treat missing argument as 0": function () {
"treats missing argument as 0": function () {
this.clock.tick();
assertEquals(0, this.clock.now);
assert.equals(this.clock.now, 0);
},
"should fire nested setTimeout calls properly": function () {
"fires nested setTimeout calls properly": function () {
var i = 0;

@@ -416,19 +419,19 @@ var clock = this.clock;

assertEquals(11, i);
assert.equals(i, 11);
},
"should not silently catch exceptions": function () {
var clock = this.clock;
"does not silently catch exceptions": function () {
var clock = this.clock;
clock.setTimeout(function() {
throw new Exception('oh no!');
}, 1000);
clock.setTimeout(function() {
throw new Exception("oh no!");
}, 1000);
assertException(function() {
clock.tick(1000);
});
assert.exception(function() {
clock.tick(1000);
});
}
});
},
testCase("ClockClearTimeoutTest", {
"clearTimeout": {
setUp: function () {

@@ -438,3 +441,3 @@ this.clock = sinon.clock.create();

"should remove timeout": function () {
"removes timeout": function () {
var stub = sinon.stub.create();

@@ -445,7 +448,7 @@ var id = this.clock.setTimeout(stub, 50);

assertFalse(stub.called);
assert.isFalse(stub.called);
}
});
},
testCase("ClockResetTest", {
"reset": {
setUp: function () {

@@ -455,3 +458,3 @@ this.clock = sinon.clock.create();

"should empty timeouts queue": function () {
"empties timeouts queue": function () {
var stub = sinon.stub.create();

@@ -462,7 +465,7 @@ this.clock.setTimeout(stub);

assertFalse(stub.called);
assert.isFalse(stub.called);
}
});
},
testCase("SetIntervalTest", {
"terval": {
setUp: function () {

@@ -472,10 +475,6 @@ this.clock = sinon.clock.create();

"should be function": function () {
assertFunction(this.clock.setInterval);
},
"should throw if no arguments": function () {
"throws if no arguments": function () {
var clock = this.clock;
assertException(function () {
assert.exception(function () {
clock.setInterval();

@@ -485,16 +484,16 @@ });

"should return numeric id": function () {
"returns numeric id": function () {
var result = this.clock.setInterval("");
assertNumber(result);
assert.isNumber(result);
},
"should return unique id": function () {
"returns unique id": function () {
var id1 = this.clock.setInterval("");
var id2 = this.clock.setInterval("");
assertNotEquals(id1, id2);
refute.equals(id2, id1);
},
"should schedule recurring timeout": function () {
"schedules recurring timeout": function () {
var stub = sinon.stub.create();

@@ -504,6 +503,6 @@ this.clock.setInterval(stub, 10);

assertEquals(9, stub.callCount);
assert.equals(stub.callCount, 9);
},
"should not schedule recurring timeout when cleared": function () {
"does not schedule recurring timeout when cleared": function () {
var clock = this.clock;

@@ -520,22 +519,33 @@ var id;

assertEquals(3, stub.callCount);
assert.equals(stub.callCount, 3);
},
"passes setTimeout parameters": function() {
var clock = sinon.clock.create();
var stub = sinon.stub.create();
clock.setInterval(stub, 2, "the first", "the second");
clock.tick(3);
assert.isTrue(stub.calledWithExactly("the first", "the second"));
}
});
},
testCase("ClockDateTest", {
"date": {
setUp: function () {
this.now = new Date().getTime() - 3000;
this.clock = sinon.clock.create(this.now);
this.Date = global.Date;
this.Date = this.global.Date;
},
tearDown: function () {
global.Date = this.Date;
this.global.Date = this.Date;
},
"should provide date constructor": function () {
assertFunction(this.clock.Date);
"provides date constructor": function () {
assert.isFunction(this.clock.Date);
},
"should create real Date objects": function () {
"creates real Date objects": function () {
var date = new this.clock.Date();

@@ -546,3 +556,3 @@

"should create real Date objects when called as function": function () {
"creates real Date objects when called as function": function () {
var date = this.clock.Date();

@@ -553,25 +563,25 @@

"should create real Date objects when Date constructor is gone": function () {
"creates real Date objects when Date constructor is gone": function () {
var realDate = new Date();
Date = function () {};
global.Date = function () {};
this.global.Date = function () {};
var date = new this.clock.Date();
assertSame(realDate.constructor.prototype, date.constructor.prototype);
assert.same(date.constructor.prototype, realDate.constructor.prototype);
},
"should create Date objects representing clock time": function () {
"creates Date objects representing clock time": function () {
var date = new this.clock.Date();
assertEquals(new Date(this.now).getTime(), date.getTime());
assert.equals(date.getTime(), new Date(this.now).getTime());
},
"should return Date object representing clock time": function () {
"returns Date object representing clock time": function () {
var date = this.clock.Date();
assertEquals(new Date(this.now).getTime(), date.getTime());
assert.equals(date.getTime(), new Date(this.now).getTime());
},
"should listen to ticking clock": function () {
"listens to ticking clock": function () {
var date1 = new this.clock.Date();

@@ -581,149 +591,164 @@ this.clock.tick(3);

assertEquals(3, date2.getTime() - date1.getTime());
assert.equals(date2.getTime() - date1.getTime(), 3);
},
"should create regular date when passing timestamp": function () {
"creates regular date when passing timestamp": function () {
var date = new Date();
var fakeDate = new this.clock.Date(date.getTime());
assertEquals(date.getTime(), fakeDate.getTime());
assert.equals(fakeDate.getTime(), date.getTime());
},
"should return regular date when calling with timestamp": function () {
"returns regular date when calling with timestamp": function () {
var date = new Date();
var fakeDate = this.clock.Date(date.getTime());
assertEquals(date.getTime(), fakeDate.getTime());
assert.equals(fakeDate.getTime(), date.getTime());
},
"should create regular date when passing year, month": function () {
"creates regular date when passing year, month": function () {
var date = new Date(2010, 4);
var fakeDate = new this.clock.Date(2010, 4);
assertEquals(date.getTime(), fakeDate.getTime());
assert.equals(fakeDate.getTime(), date.getTime());
},
"should return regular date when calling with year, month": function () {
"returns regular date when calling with year, month": function () {
var date = new Date(2010, 4);
var fakeDate = this.clock.Date(2010, 4);
assertEquals(date.getTime(), fakeDate.getTime());
assert.equals(fakeDate.getTime(), date.getTime());
},
"should create regular date when passing y, m, d": function () {
"creates regular date when passing y, m, d": function () {
var date = new Date(2010, 4, 2);
var fakeDate = new this.clock.Date(2010, 4, 2);
assertEquals(date.getTime(), fakeDate.getTime());
assert.equals(fakeDate.getTime(), date.getTime());
},
"should return regular date when calling with y, m, d": function () {
"returns regular date when calling with y, m, d": function () {
var date = new Date(2010, 4, 2);
var fakeDate = this.clock.Date(2010, 4, 2);
assertEquals(date.getTime(), fakeDate.getTime());
assert.equals(fakeDate.getTime(), date.getTime());
},
"should create regular date when passing y, m, d, h": function () {
"creates regular date when passing y, m, d, h": function () {
var date = new Date(2010, 4, 2, 12);
var fakeDate = new this.clock.Date(2010, 4, 2, 12);
assertEquals(date.getTime(), fakeDate.getTime());
assert.equals(fakeDate.getTime(), date.getTime());
},
"should return regular date when calling with y, m, d, h": function () {
"returns regular date when calling with y, m, d, h": function () {
var date = new Date(2010, 4, 2, 12);
var fakeDate = this.clock.Date(2010, 4, 2, 12);
assertEquals(date.getTime(), fakeDate.getTime());
assert.equals(fakeDate.getTime(), date.getTime());
},
"should create regular date when passing y, m, d, h, m": function () {
"creates regular date when passing y, m, d, h, m": function () {
var date = new Date(2010, 4, 2, 12, 42);
var fakeDate = new this.clock.Date(2010, 4, 2, 12, 42);
assertEquals(date.getTime(), fakeDate.getTime());
assert.equals(fakeDate.getTime(), date.getTime());
},
"should return regular date when calling with y, m, d, h, m": function () {
"returns regular date when calling with y, m, d, h, m": function () {
var date = new Date(2010, 4, 2, 12, 42);
var fakeDate = this.clock.Date(2010, 4, 2, 12, 42);
assertEquals(date.getTime(), fakeDate.getTime());
assert.equals(fakeDate.getTime(), date.getTime());
},
"should create regular date when passing y, m, d, h, m, s": function () {
"creates regular date when passing y, m, d, h, m, s": function () {
var date = new Date(2010, 4, 2, 12, 42, 53);
var fakeDate = new this.clock.Date(2010, 4, 2, 12, 42, 53);
assertEquals(date.getTime(), fakeDate.getTime());
assert.equals(fakeDate.getTime(), date.getTime());
},
"should return regular date when calling with y, m, d, h, m, s": function () {
"returns regular date when calling with y, m, d, h, m, s": function () {
var date = new Date(2010, 4, 2, 12, 42, 53);
var fakeDate = this.clock.Date(2010, 4, 2, 12, 42, 53);
assertEquals(date.getTime(), fakeDate.getTime());
assert.equals(fakeDate.getTime(), date.getTime());
},
"should create regular date when passing y, m, d, h, m, s, ms": function () {
"creates regular date when passing y, m, d, h, m, s, ms": function () {
var date = new Date(2010, 4, 2, 12, 42, 53, 498);
var fakeDate = new this.clock.Date(2010, 4, 2, 12, 42, 53, 498);
assertEquals(date.getTime(), fakeDate.getTime());
assert.equals(fakeDate.getTime(), date.getTime());
},
"should return regular date when calling with y, m, d, h, m, s, ms": function () {
"returns regular date when calling with y, m, d, h, m, s, ms": function () {
var date = new Date(2010, 4, 2, 12, 42, 53, 498);
var fakeDate = this.clock.Date(2010, 4, 2, 12, 42, 53, 498);
assertEquals(date.getTime(), fakeDate.getTime());
assert.equals(fakeDate.getTime(), date.getTime());
},
"should mirror native Date.prototype": function () {
assertSame(Date.prototype, this.clock.Date.prototype);
"mirrors native Date.prototype": function () {
assert.same(this.clock.Date.prototype, Date.prototype);
},
"should support now method if present": function () {
assertSame(typeof Date.now, typeof this.clock.Date.now);
"supports now method if present": function () {
assert.same(typeof this.clock.Date.now, typeof Date.now);
},
"now should return clock.now if native date supports it": function () {
if (Date.now) {
assertEquals(this.now, this.clock.Date.now());
} else {
jstestdriver.console.log("Environment does not support Date.now");
assertUndefined(this.clock.Date.now);
"now": {
requiresSupportFor: { "Date.now": !!Date.now },
"returns clock.now": function () {
assert.equals(this.clock.Date.now(), this.now);
}
},
"should mirror parse method": function () {
assertSame(Date.parse, this.clock.Date.parse);
"unsupported now": {
requiresSupportFor: { "No Date.now implementation": !Date.now },
"is undefined": function () {
refute.defined(this.clock.Date.now);
}
},
"should mirror UTC method": function () {
assertSame(Date.UTC, this.clock.Date.UTC);
"mirrors parse method": function () {
assert.same(this.clock.Date.parse, Date.parse);
},
"should mirror toUTCString method": function () {
assertSame(Date.prototype.toUTCString, this.clock.Date.prototype.toUTCString);
"mirrors UTC method": function () {
assert.same(this.clock.Date.UTC, Date.UTC);
},
"should mirror toSource if supported": function () {
if (Date.toSource) {
assertSame(Date.toSource(), this.clock.Date.toSource());
} else {
jstestdriver.console.log("Environment does not support Date.toSource");
assertUndefined(this.clock.Date.toSource);
"mirrors toUTCString method": function () {
assert.same(this.clock.Date.prototype.toUTCString, Date.prototype.toUTCString);
},
"toSource": {
requiresSupportFor: { "Date.toSource": !!Date.toSource },
"is mirrored": function () {
assert.same(this.clock.Date.toSource(), Date.toSource());
}
},
"should mirror toString": function () {
assertSame(Date.toString(), this.clock.Date.toString());
"unsupported toSource": {
requiresSupportFor: { "No Date.toSource implementation": !Date.toSource },
"is undefined": function () {
refute.defined(this.clock.Date.toSource);
}
},
"mirrors toString": function () {
assert.same(this.clock.Date.toString(), Date.toString());
}
});
},
testCase("SinonStubTimersTest", {
"stubTimers": {
setUp: function () {
this.dateNow = global.Date.now;
this.dateNow = this.global.Date.now;
},

@@ -738,32 +763,32 @@

if (typeof this.dateNow == "undefined") {
delete global.Date.now;
delete this.global.Date.now;
} else {
global.Date.now = this.dateNow;
this.global.Date.now = this.dateNow;
}
},
"should return clock object": function () {
"returns clock object": function () {
this.clock = sinon.useFakeTimers();
assertObject(this.clock);
assertFunction(this.clock.tick);
assert.isObject(this.clock);
assert.isFunction(this.clock.tick);
},
"should have clock property": function () {
"haves clock property": function () {
this.clock = sinon.useFakeTimers();
assertSame(this.clock, setTimeout.clock);
assertSame(this.clock, clearTimeout.clock);
assertSame(this.clock, setInterval.clock);
assertSame(this.clock, clearInterval.clock);
assertSame(this.clock, Date.clock);
assert.same(setTimeout.clock, this.clock);
assert.same(clearTimeout.clock, this.clock);
assert.same(setInterval.clock, this.clock);
assert.same(clearInterval.clock, this.clock);
assert.same(Date.clock, this.clock);
},
"should set initial timestamp": function () {
"sets initial timestamp": function () {
this.clock = sinon.useFakeTimers(1400);
assertEquals(1400, this.clock.now);
assert.equals(this.clock.now, 1400);
},
"should replace global setTimeout": function () {
"replaces global setTimeout": function () {
this.clock = sinon.useFakeTimers();

@@ -784,6 +809,6 @@ var stub = sinon.stub.create();

assertNumber(id);
assert.isNumber(id);
},
"should replace global clearTimeout": function () {
"replaces global clearTimeout": function () {
this.clock = sinon.useFakeTimers();

@@ -795,6 +820,6 @@ var stub = sinon.stub.create();

assertFalse(stub.called);
assert.isFalse(stub.called);
},
"should restore global setTimeout": function () {
"restores global setTimeout": function () {
this.clock = sinon.useFakeTimers();

@@ -807,7 +832,7 @@ var stub = sinon.stub.create();

assertFalse(stub.called);
assertSame(sinon.timers.setTimeout, setTimeout);
assert.isFalse(stub.called);
assert.same(setTimeout, sinon.timers.setTimeout);
},
"should restore global clearTimeout": function () {
"restores global clearTimeout": function () {
this.clock = sinon.useFakeTimers();

@@ -817,6 +842,6 @@ sinon.stub.create();

assertSame(sinon.timers.clearTimeout, clearTimeout);
assert.same(clearTimeout, sinon.timers.clearTimeout);
},
"should replace global setInterval": function () {
"replaces global setInterval": function () {
this.clock = sinon.useFakeTimers();

@@ -831,3 +856,3 @@ var stub = sinon.stub.create();

"should replace global clearInterval": function () {
"replaces global clearInterval": function () {
this.clock = sinon.useFakeTimers();

@@ -839,6 +864,6 @@ var stub = sinon.stub.create();

assertFalse(stub.called);
assert.isFalse(stub.called);
},
"should restore global setInterval": function () {
"restores global setInterval": function () {
this.clock = sinon.useFakeTimers();

@@ -851,7 +876,7 @@ var stub = sinon.stub.create();

assertFalse(stub.called);
assertSame(sinon.timers.setInterval, setInterval);
assert.isFalse(stub.called);
assert.same(setInterval, sinon.timers.setInterval);
},
"should restore global clearInterval": function () {
"restores global clearInterval": function () {
this.clock = sinon.useFakeTimers();

@@ -861,11 +886,33 @@ sinon.stub.create();

assertSame(sinon.timers.clearInterval, clearInterval);
assert.same(clearInterval, sinon.timers.clearInterval);
},
"should fake Date constructor": function () {
"//deletes global property if it originally did not have own property":
"Not quite sure why this test was initially commented out - TODO: Fix"
/*function () {
// remove this properties from the global object ("hasOwnProperty" false)
// delete this.global.clearTimeout;
// delete this.global.setInterval;
// // set these properties to the global object ("hasOwnProperty" true)
// this.global.clearInterval = this.global.clearInterval;
// this.global.setTimeout = this.global.clearInterval;
// this.clock = sinon.useFakeTimers();
// this.clock.restore();
// // these properties should be removed from the global object directly.
// assert.isFalse(this.global.hasOwnProperty("clearTimeout"));
// assert.isFalse(this.global.hasOwnProperty("setInterval"));
// // these properties should be added back into the global object directly.
// assert(this.global.hasOwnProperty("clearInterval"));
// assert(this.global.hasOwnProperty("setTimeout"));
}*/,
"fakes Date constructor": function () {
this.clock = sinon.useFakeTimers(0);
var now = new Date();
assertNotSame(sinon.timers.Date, Date);
assertEquals(0, now.getTime());
refute.same(Date, sinon.timers.Date);
assert.equals(now.getTime(), 0);
},

@@ -881,51 +928,51 @@

"decide on Date.now support at call-time when supported": function () {
global.Date.now = function () {};
this.global.Date.now = function () {};
this.clock = sinon.useFakeTimers(0);
assertEquals("function", typeof Date.now);
assert.equals(typeof Date.now, "function");
},
"decide on Date.now support at call-time when unsupported": function () {
global.Date.now = null;
this.global.Date.now = null;
this.clock = sinon.useFakeTimers(0);
assertUndefined(Date.now);
refute.defined(Date.now);
},
"should restore Date constructor": function () {
"restores Date constructor": function () {
this.clock = sinon.useFakeTimers(0);
this.clock.restore();
assertSame(sinon.timers.Date, Date);
assert.same(Date, sinon.timers.Date);
},
"should fake provided methods": function () {
"fakes provided methods": function () {
this.clock = sinon.useFakeTimers("setTimeout", "Date");
assertNotSame(sinon.timers.setTimeout, setTimeout);
assertNotSame(sinon.timers.Date, Date);
refute.same(setTimeout, sinon.timers.setTimeout);
refute.same(Date, sinon.timers.Date);
},
"should reset faked methods": function () {
"resets faked methods": function () {
this.clock = sinon.useFakeTimers("setTimeout", "Date");
this.clock.restore();
assertSame(sinon.timers.setTimeout, setTimeout);
assertSame(sinon.timers.Date, Date);
assert.same(setTimeout, sinon.timers.setTimeout);
assert.same(Date, sinon.timers.Date);
},
"should not fake methods not provided": function () {
"does not fake methods not provided": function () {
this.clock = sinon.useFakeTimers("setTimeout", "Date");
assertSame(sinon.timers.clearTimeout, clearTimeout);
assertSame(sinon.timers.setInterval, setInterval);
assertSame(sinon.timers.clearInterval, clearInterval);
assert.same(clearTimeout, sinon.timers.clearTimeout);
assert.same(setInterval, sinon.timers.setInterval);
assert.same(clearInterval, sinon.timers.clearInterval);
},
"should not be able to use date object for now": function () {
assertException(function () {
"does not be able to use date object for now": function () {
assert.exception(function () {
sinon.useFakeTimers(new Date(2011, 9, 1));
});
}
});
}(typeof global != "undefined" ? global : this));
}
});
/*jslint onevar: false, eqeqeq: false, browser: true*/
/*globals window
jstestdriver
XMLHttpRequest
ActiveXObject
testCase
sinon
assert
assertSame
assertNotSame
assertEquals
assertTrue
assertFalse
assertNull
assertNotNull
assertException
assertNoException
assertUndefined
assertObject
assertFunction*/
/*globals window XMLHttpRequest ActiveXObject sinon buster*/
/**

@@ -25,3 +7,3 @@ * @author Christian Johansen (christian@cjohansen.no)

*
* Copyright (c) 2010-2011 Christian Johansen
* Copyright (c) 2010-2012 Christian Johansen
*/

@@ -31,3 +13,26 @@ "use strict";

(function (global) {
testCase("FakeXMLHttpRequestTest", {
var globalXMLHttpRequest = global.XMLHttpRequest;
var globalActiveXObject = global.ActiveXObject;
var fakeXhrSetUp = function () {
this.fakeXhr = sinon.useFakeXMLHttpRequest();
};
var fakeXhrTearDown = function () {
if (typeof this.fakeXhr.restore == "function") {
this.fakeXhr.restore();
}
};
var runWithWorkingXHROveride = function(workingXHR,test) {
try {
var original = sinon.xhr.workingXHR;
sinon.xhr.workingXHR = workingXHR;
test();
} finally {
sinon.xhr.workingXHR = original;
}
};
buster.testCase("sinon.FakeXMLHttpRequest", {
tearDown: function () {

@@ -37,15 +42,15 @@ delete sinon.FakeXMLHttpRequest.onCreate;

"should be constructor": function () {
assertFunction(sinon.FakeXMLHttpRequest);
assertSame(sinon.FakeXMLHttpRequest, sinon.FakeXMLHttpRequest.prototype.constructor);
"is constructor": function () {
assert.isFunction(sinon.FakeXMLHttpRequest);
assert.same(sinon.FakeXMLHttpRequest.prototype.constructor, sinon.FakeXMLHttpRequest);
},
"should implement readyState constants": function () {
assertSame(1, sinon.FakeXMLHttpRequest.OPENED);
assertSame(2, sinon.FakeXMLHttpRequest.HEADERS_RECEIVED);
assertSame(3, sinon.FakeXMLHttpRequest.LOADING);
assertSame(4, sinon.FakeXMLHttpRequest.DONE);
"implements readyState constants": function () {
assert.same(sinon.FakeXMLHttpRequest.OPENED, 1);
assert.same(sinon.FakeXMLHttpRequest.HEADERS_RECEIVED, 2);
assert.same(sinon.FakeXMLHttpRequest.LOADING, 3);
assert.same(sinon.FakeXMLHttpRequest.DONE, 4);
},
"should call onCreate if listener is set": function () {
"calls onCreate if listener is set": function () {
var onCreate = sinon.spy();

@@ -59,3 +64,3 @@ sinon.FakeXMLHttpRequest.onCreate = onCreate;

"should pass new object to onCreate if set": function () {
"passes new object to onCreate if set": function () {
var onCreate = sinon.spy();

@@ -66,1077 +71,1063 @@ sinon.FakeXMLHttpRequest.onCreate = onCreate;

assertSame(xhr, onCreate.getCall(0).args[0]);
}
});
testCase("FakeXMLHttpRequestOpenTest", {
setUp: function () {
this.xhr = new sinon.FakeXMLHttpRequest();
assert.same(onCreate.getCall(0).args[0], xhr);
},
"should be method": function () {
assertFunction(this.xhr.open);
},
"open": {
setUp: function () {
this.xhr = new sinon.FakeXMLHttpRequest();
},
"should set properties on object": function () {
this.xhr.open("GET", "/my/url", true, "cjno", "pass");
"is method": function () {
assert.isFunction(this.xhr.open);
},
assertEquals("GET", this.xhr.method);
assertEquals("/my/url", this.xhr.url);
assertTrue(this.xhr.async);
assertEquals("cjno", this.xhr.username);
assertEquals("pass", this.xhr.password);
},
"sets properties on object": function () {
this.xhr.open("GET", "/my/url", true, "cjno", "pass");
"should be async by default": function () {
this.xhr.open("GET", "/my/url");
assert.equals(this.xhr.method, "GET");
assert.equals(this.xhr.url, "/my/url");
assert.isTrue(this.xhr.async);
assert.equals(this.xhr.username, "cjno");
assert.equals(this.xhr.password, "pass");
},
assertTrue(this.xhr.async);
},
"is async by default": function () {
this.xhr.open("GET", "/my/url");
"should set async to false": function () {
this.xhr.open("GET", "/my/url", false);
assert.isTrue(this.xhr.async);
},
assertFalse(this.xhr.async);
},
"sets async to false": function () {
this.xhr.open("GET", "/my/url", false);
"should set responseText to null": function () {
this.xhr.open("GET", "/my/url");
assert.isFalse(this.xhr.async);
},
assertNull(this.xhr.responseText);
},
"sets responseText to null": function () {
this.xhr.open("GET", "/my/url");
"should set requestHeaders to blank object": function () {
this.xhr.open("GET", "/my/url");
assert.isNull(this.xhr.responseText);
},
assertObject(this.xhr.requestHeaders);
assertEquals({}, this.xhr.requestHeaders);
},
"sets requestHeaders to blank object": function () {
this.xhr.open("GET", "/my/url");
"should set readyState to OPENED": function () {
this.xhr.open("GET", "/my/url");
assert.isObject(this.xhr.requestHeaders);
assert.equals(this.xhr.requestHeaders, {});
},
assertSame(sinon.FakeXMLHttpRequest.OPENED, this.xhr.readyState);
},
"sets readyState to OPENED": function () {
this.xhr.open("GET", "/my/url");
"should set send flag to false": function () {
this.xhr.open("GET", "/my/url");
assert.same(this.xhr.readyState, sinon.FakeXMLHttpRequest.OPENED);
},
assertFalse(this.xhr.sendFlag);
},
"sets send flag to false": function () {
this.xhr.open("GET", "/my/url");
"should dispatch onreadystatechange with reset state": function () {
var state = {};
assert.isFalse(this.xhr.sendFlag);
},
this.xhr.onreadystatechange = function () {
sinon.extend(state, this);
};
"dispatches onreadystatechange with reset state": function () {
var state = {};
this.xhr.open("GET", "/my/url");
this.xhr.onreadystatechange = function () {
sinon.extend(state, this);
};
assertEquals("GET", state.method);
assertEquals("/my/url", state.url);
assertTrue(state.async);
assertUndefined(state.username);
assertUndefined(state.password);
assertNull(state.responseText);
assertUndefined(state.responseHeaders);
assertEquals(sinon.FakeXMLHttpRequest.OPENED, state.readyState);
assertFalse(state.sendFlag);
}
});
this.xhr.open("GET", "/my/url");
testCase("FakeXMLHttpRequestSetRequestHeaderTest", {
setUp: function () {
this.xhr = new sinon.FakeXMLHttpRequest();
this.xhr.open("GET", "/");
assert.equals(state.method, "GET");
assert.equals(state.url, "/my/url");
assert.isTrue(state.async);
refute.defined(state.username);
refute.defined(state.password);
assert.isNull(state.responseText);
refute.defined(state.responseHeaders);
assert.equals(state.readyState, sinon.FakeXMLHttpRequest.OPENED);
assert.isFalse(state.sendFlag);
}
},
"should throw exception if readyState is not OPENED": function () {
var xhr = new sinon.FakeXMLHttpRequest();
"setRequestHeader": {
setUp: function () {
this.xhr = new sinon.FakeXMLHttpRequest();
this.xhr.open("GET", "/");
},
assertException(function () {
xhr.setRequestHeader("X-EY", "No-no");
});
},
"throws exception if readyState is not OPENED": function () {
var xhr = new sinon.FakeXMLHttpRequest();
"should throw exception if send flag is true": function () {
var xhr = this.xhr;
xhr.sendFlag = true;
assert.exception(function () {
xhr.setRequestHeader("X-EY", "No-no");
});
},
assertException(function () {
xhr.setRequestHeader("X-EY", "No-no");
});
},
"throws exception if send flag is true": function () {
var xhr = this.xhr;
xhr.sendFlag = true;
"should disallow unsafe headers": function () {
var xhr = this.xhr;
assert.exception(function () {
xhr.setRequestHeader("X-EY", "No-no");
});
},
assertException(function () {
xhr.setRequestHeader("Accept-Charset", "");
});
"disallows unsafe headers": function () {
var xhr = this.xhr;
assertException(function () {
xhr.setRequestHeader("Accept-Encoding", "");
});
assert.exception(function () {
xhr.setRequestHeader("Accept-Charset", "");
});
assertException(function () {
xhr.setRequestHeader("Connection", "");
});
assert.exception(function () {
xhr.setRequestHeader("Accept-Encoding", "");
});
assertException(function () {
xhr.setRequestHeader("Content-Length", "");
});
assert.exception(function () {
xhr.setRequestHeader("Connection", "");
});
assertException(function () {
xhr.setRequestHeader("Cookie", "");
});
assert.exception(function () {
xhr.setRequestHeader("Content-Length", "");
});
assertException(function () {
xhr.setRequestHeader("Cookie2", "");
});
assert.exception(function () {
xhr.setRequestHeader("Cookie", "");
});
assertException(function () {
xhr.setRequestHeader("Content-Transfer-Encoding", "");
});
assert.exception(function () {
xhr.setRequestHeader("Cookie2", "");
});
assertException(function () {
xhr.setRequestHeader("Date", "");
});
assert.exception(function () {
xhr.setRequestHeader("Content-Transfer-Encoding", "");
});
assertException(function () {
xhr.setRequestHeader("Expect", "");
});
assert.exception(function () {
xhr.setRequestHeader("Date", "");
});
assertException(function () {
xhr.setRequestHeader("Host", "");
});
assert.exception(function () {
xhr.setRequestHeader("Expect", "");
});
assertException(function () {
xhr.setRequestHeader("Keep-Alive", "");
});
assert.exception(function () {
xhr.setRequestHeader("Host", "");
});
assertException(function () {
xhr.setRequestHeader("Referer", "");
});
assert.exception(function () {
xhr.setRequestHeader("Keep-Alive", "");
});
assertException(function () {
xhr.setRequestHeader("TE", "");
});
assert.exception(function () {
xhr.setRequestHeader("Referer", "");
});
assertException(function () {
xhr.setRequestHeader("Trailer", "");
});
assert.exception(function () {
xhr.setRequestHeader("TE", "");
});
assertException(function () {
xhr.setRequestHeader("Transfer-Encoding", "");
});
assert.exception(function () {
xhr.setRequestHeader("Trailer", "");
});
assertException(function () {
xhr.setRequestHeader("Upgrade", "");
});
assert.exception(function () {
xhr.setRequestHeader("Transfer-Encoding", "");
});
assertException(function () {
xhr.setRequestHeader("User-Agent", "");
});
assert.exception(function () {
xhr.setRequestHeader("Upgrade", "");
});
assertException(function () {
xhr.setRequestHeader("Via", "");
});
assert.exception(function () {
xhr.setRequestHeader("User-Agent", "");
});
assertException(function () {
xhr.setRequestHeader("Proxy-Oops", "");
});
assert.exception(function () {
xhr.setRequestHeader("Via", "");
});
assertException(function () {
xhr.setRequestHeader("Sec-Oops", "");
});
},
assert.exception(function () {
xhr.setRequestHeader("Proxy-Oops", "");
});
"should set header and value": function () {
this.xhr.setRequestHeader("X-Fake", "Yeah!");
assert.exception(function () {
xhr.setRequestHeader("Sec-Oops", "");
});
},
assertEquals({ "X-Fake": "Yeah!" }, this.xhr.requestHeaders);
},
"sets header and value": function () {
this.xhr.setRequestHeader("X-Fake", "Yeah!");
"should append same-named header values": function () {
this.xhr.setRequestHeader("X-Fake", "Oh");
this.xhr.setRequestHeader("X-Fake", "yeah!");
assert.equals(this.xhr.requestHeaders, { "X-Fake": "Yeah!" });
},
assertEquals({ "X-Fake": "Oh,yeah!" }, this.xhr.requestHeaders);
}
});
"appends same-named header values": function () {
this.xhr.setRequestHeader("X-Fake", "Oh");
this.xhr.setRequestHeader("X-Fake", "yeah!");
testCase("FakeXMLHttpRequestSendTest", {
setUp: function () {
this.xhr = new sinon.FakeXMLHttpRequest();
assert.equals(this.xhr.requestHeaders, { "X-Fake": "Oh,yeah!" });
}
},
"should throw if request is not open": function () {
var xhr = new sinon.FakeXMLHttpRequest();
"send": {
setUp: function () {
this.xhr = new sinon.FakeXMLHttpRequest();
},
assertException(function () {
xhr.send();
});
},
"throws if request is not open": function () {
var xhr = new sinon.FakeXMLHttpRequest();
"should throw if send flag is true": function () {
var xhr = this.xhr;
xhr.open("GET", "/");
xhr.sendFlag = true;
assert.exception(function () {
xhr.send();
});
},
assertException(function () {
xhr.send();
});
},
"throws if send flag is true": function () {
var xhr = this.xhr;
xhr.open("GET", "/");
xhr.sendFlag = true;
"should set GET body to null": function () {
this.xhr.open("GET", "/");
this.xhr.send("Data");
assert.exception(function () {
xhr.send();
});
},
assertNull(this.xhr.requestBody);
},
"sets GET body to null": function () {
this.xhr.open("GET", "/");
this.xhr.send("Data");
"should set HEAD body to null": function () {
this.xhr.open("HEAD", "/");
this.xhr.send("Data");
assert.isNull(this.xhr.requestBody);
},
assertNull(this.xhr.requestBody);
},
"sets HEAD body to null": function () {
this.xhr.open("HEAD", "/");
this.xhr.send("Data");
"should set mime to text/plain": function () {
this.xhr.open("POST", "/");
this.xhr.send("Data");
assert.isNull(this.xhr.requestBody);
},
assertEquals("text/plain;charset=utf-8", this.xhr.requestHeaders["Content-Type"]);
},
"sets mime to text/plain": function () {
this.xhr.open("POST", "/");
this.xhr.send("Data");
"should not override mime": function () {
this.xhr.open("POST", "/");
this.xhr.setRequestHeader("Content-Type", "text/html");
this.xhr.send("Data");
assert.equals(this.xhr.requestHeaders["Content-Type"], "text/plain;charset=utf-8");
},
assertEquals("text/html;charset=utf-8", this.xhr.requestHeaders["Content-Type"]);
},
"does not override mime": function () {
this.xhr.open("POST", "/");
this.xhr.setRequestHeader("Content-Type", "text/html");
this.xhr.send("Data");
"should set request body to string data": function () {
this.xhr.open("POST", "/");
this.xhr.send("Data");
assert.equals(this.xhr.requestHeaders["Content-Type"], "text/html;charset=utf-8");
},
assertEquals("Data", this.xhr.requestBody);
},
"sets request body to string data": function () {
this.xhr.open("POST", "/");
this.xhr.send("Data");
"should set error flag to false": function () {
this.xhr.open("POST", "/");
this.xhr.send("Data");
assert.equals(this.xhr.requestBody, "Data");
},
assertFalse(this.xhr.errorFlag);
},
"sets error flag to false": function () {
this.xhr.open("POST", "/");
this.xhr.send("Data");
"should set send flag to true": function () {
this.xhr.open("POST", "/");
this.xhr.send("Data");
assert.isFalse(this.xhr.errorFlag);
},
assertTrue(this.xhr.sendFlag);
},
"sets send flag to true": function () {
this.xhr.open("POST", "/");
this.xhr.send("Data");
"should not set send flag to true if sync": function () {
this.xhr.open("POST", "/", false);
this.xhr.send("Data");
assert.isTrue(this.xhr.sendFlag);
},
assertFalse(this.xhr.sendFlag);
},
"does not set send flag to true if sync": function () {
this.xhr.open("POST", "/", false);
this.xhr.send("Data");
"should dispatch onreadystatechange": function () {
var state;
this.xhr.open("POST", "/", false);
assert.isFalse(this.xhr.sendFlag);
},
this.xhr.onreadystatechange = function () {
state = this.readyState;
};
"dispatches onreadystatechange": function () {
var state;
this.xhr.open("POST", "/", false);
this.xhr.send("Data");
this.xhr.onreadystatechange = function () {
state = this.readyState;
};
assertEquals(sinon.FakeXMLHttpRequest.OPENED, state);
},
this.xhr.send("Data");
"should dispatch event using DOM Event interface": function () {
var listener = sinon.spy();
this.xhr.open("POST", "/", false);
this.xhr.addEventListener("readystatechange", listener);
assert.equals(state, sinon.FakeXMLHttpRequest.OPENED);
},
this.xhr.send("Data");
"dispatches event using DOM Event interface": function () {
var listener = sinon.spy();
this.xhr.open("POST", "/", false);
this.xhr.addEventListener("readystatechange", listener);
assert(listener.calledOnce);
assertEquals("readystatechange", listener.args[0][0].type);
},
this.xhr.send("Data");
"should dispatch onSend callback if set": function () {
this.xhr.open("POST", "/", true);
var callback = sinon.spy();
this.xhr.onSend = callback;
assert(listener.calledOnce);
assert.equals(listener.args[0][0].type, "readystatechange");
},
this.xhr.send("Data");
"dispatches onSend callback if set": function () {
this.xhr.open("POST", "/", true);
var callback = sinon.spy();
this.xhr.onSend = callback;
assert(callback.called);
},
this.xhr.send("Data");
"should dispatch onSend with request as argument": function () {
this.xhr.open("POST", "/", true);
var callback = sinon.spy();
this.xhr.onSend = callback;
assert(callback.called);
},
this.xhr.send("Data");
"dispatches onSend with request as argument": function () {
this.xhr.open("POST", "/", true);
var callback = sinon.spy();
this.xhr.onSend = callback;
assert(callback.calledWith(this.xhr));
},
this.xhr.send("Data");
"should dispatch onSend when async": function () {
this.xhr.open("POST", "/", false);
var callback = sinon.spy();
this.xhr.onSend = callback;
assert(callback.calledWith(this.xhr));
},
this.xhr.send("Data");
"dispatches onSend when async": function () {
this.xhr.open("POST", "/", false);
var callback = sinon.spy();
this.xhr.onSend = callback;
assert(callback.calledWith(this.xhr));
}
});
this.xhr.send("Data");
testCase("FakeXMLHttpRequestSetResponseHeadersTest", {
setUp: function () {
this.xhr = new sinon.FakeXMLHttpRequest();
assert(callback.calledWith(this.xhr));
}
},
"should set request headers": function () {
var object = { id: 42 };
this.xhr.open("GET", "/");
this.xhr.send();
this.xhr.setResponseHeaders(object);
"setResponseHeaders": {
setUp: function () {
this.xhr = new sinon.FakeXMLHttpRequest();
},
assertEquals(object, this.xhr.responseHeaders);
},
"sets request headers": function () {
var object = { id: 42 };
this.xhr.open("GET", "/");
this.xhr.send();
this.xhr.setResponseHeaders(object);
"should call readyStateChange with HEADERS_RECEIVED": function () {
var object = { id: 42 };
this.xhr.open("GET", "/");
this.xhr.send();
var spy = this.xhr.readyStateChange = sinon.spy();
assert.equals(this.xhr.responseHeaders, object);
},
this.xhr.setResponseHeaders(object);
"calls readyStateChange with HEADERS_RECEIVED": function () {
var object = { id: 42 };
this.xhr.open("GET", "/");
this.xhr.send();
var spy = this.xhr.readyStateChange = sinon.spy();
assert(spy.calledWith(sinon.FakeXMLHttpRequest.HEADERS_RECEIVED));
},
this.xhr.setResponseHeaders(object);
"should not call readyStateChange if sync": function () {
var object = { id: 42 };
this.xhr.open("GET", "/", false);
this.xhr.send();
var spy = this.xhr.readyStateChange = sinon.spy();
assert(spy.calledWith(sinon.FakeXMLHttpRequest.HEADERS_RECEIVED));
},
this.xhr.setResponseHeaders(object);
"does not call readyStateChange if sync": function () {
var object = { id: 42 };
this.xhr.open("GET", "/", false);
this.xhr.send();
var spy = this.xhr.readyStateChange = sinon.spy();
assertFalse(spy.called);
}
});
this.xhr.setResponseHeaders(object);
testCase("FakeXMLHttpRequestSetResponseBodyAsyncTest", {
setUp: function () {
this.xhr = new sinon.FakeXMLHttpRequest();
this.xhr.open("GET", "/");
this.xhr.send();
this.xhr.setResponseHeaders({});
assert.isFalse(spy.called);
}
},
"should invoke onreadystatechange handler with LOADING state": function () {
var spy = sinon.spy();
this.xhr.readyStateChange = spy;
"setResponseBodyAsync": {
setUp: function () {
this.xhr = new sinon.FakeXMLHttpRequest();
this.xhr.open("GET", "/");
this.xhr.send();
this.xhr.setResponseHeaders({});
},
this.xhr.setResponseBody("Some text goes in here ok?");
"invokes onreadystatechange handler with LOADING state": function () {
var spy = sinon.spy();
this.xhr.readyStateChange = spy;
assert(spy.calledWith(sinon.FakeXMLHttpRequest.LOADING));
},
this.xhr.setResponseBody("Some text goes in here ok?");
"should invoke onreadystatechange handler for each 10 byte chunk": function () {
var spy = sinon.spy();
this.xhr.readyStateChange = spy;
this.xhr.chunkSize = 10;
assert(spy.calledWith(sinon.FakeXMLHttpRequest.LOADING));
},
this.xhr.setResponseBody("Some text goes in here ok?");
"invokes onreadystatechange handler for each 10 byte chunk": function () {
var spy = sinon.spy();
this.xhr.readyStateChange = spy;
this.xhr.chunkSize = 10;
assertEquals(4, spy.callCount);
},
this.xhr.setResponseBody("Some text goes in here ok?");
"should invoke onreadystatechange handler for each x byte chunk": function () {
var spy = sinon.spy();
this.xhr.readyStateChange = spy;
this.xhr.chunkSize = 20;
assert.equals(spy.callCount, 4);
},
this.xhr.setResponseBody("Some text goes in here ok?");
"invokes onreadystatechange handler for each x byte chunk": function () {
var spy = sinon.spy();
this.xhr.readyStateChange = spy;
this.xhr.chunkSize = 20;
assertEquals(3, spy.callCount);
},
this.xhr.setResponseBody("Some text goes in here ok?");
"should invoke onreadystatechange handler with partial data": function () {
var pieces = [];
assert.equals(spy.callCount, 3);
},
var spy = sinon.spy(function () {
pieces.push(this.responseText);
});
"invokes onreadystatechange handler with partial data": function () {
var pieces = [];
this.xhr.readyStateChange = spy;
this.xhr.chunkSize = 9;
var spy = sinon.spy(function () {
pieces.push(this.responseText);
});
this.xhr.setResponseBody("Some text goes in here ok?");
this.xhr.readyStateChange = spy;
this.xhr.chunkSize = 9;
assertEquals("Some text", pieces[1]);
},
this.xhr.setResponseBody("Some text goes in here ok?");
"should call onreadystatechange with DONE state": function () {
var spy = sinon.spy();
this.xhr.readyStateChange = spy;
assert.equals(pieces[1], "Some text");
},
this.xhr.setResponseBody("Some text goes in here ok?");
"calls onreadystatechange with DONE state": function () {
var spy = sinon.spy();
this.xhr.readyStateChange = spy;
assert(spy.calledWith(sinon.FakeXMLHttpRequest.DONE));
},
this.xhr.setResponseBody("Some text goes in here ok?");
"should throw if not open": function () {
var xhr = new sinon.FakeXMLHttpRequest();
assert(spy.calledWith(sinon.FakeXMLHttpRequest.DONE));
},
assertException(function () {
xhr.setResponseBody("");
});
},
"throws if not open": function () {
var xhr = new sinon.FakeXMLHttpRequest();
"should throw if no headers received": function () {
var xhr = new sinon.FakeXMLHttpRequest();
xhr.open("GET", "/");
xhr.send();
assert.exception(function () {
xhr.setResponseBody("");
});
},
assertException(function () {
xhr.setResponseBody("");
});
},
"throws if no headers received": function () {
var xhr = new sinon.FakeXMLHttpRequest();
xhr.open("GET", "/");
xhr.send();
"should throw if body was already sent": function () {
var xhr = new sinon.FakeXMLHttpRequest();
xhr.open("GET", "/");
xhr.send();
xhr.setResponseHeaders({});
xhr.setResponseBody("");
assert.exception(function () {
xhr.setResponseBody("");
});
},
assertException(function () {
"throws if body was already sent": function () {
var xhr = new sinon.FakeXMLHttpRequest();
xhr.open("GET", "/");
xhr.send();
xhr.setResponseHeaders({});
xhr.setResponseBody("");
});
},
"should throw if body is not a string": function () {
var xhr = new sinon.FakeXMLHttpRequest();
xhr.open("GET", "/");
xhr.send();
xhr.setResponseHeaders({});
assert.exception(function () {
xhr.setResponseBody("");
});
},
assertException(function () {
xhr.setResponseBody({});
}, "InvalidBodyException");
}
});
"throws if body is not a string": function () {
var xhr = new sinon.FakeXMLHttpRequest();
xhr.open("GET", "/");
xhr.send();
xhr.setResponseHeaders({});
testCase("FakeXMLHttpRequestSetResponseBodySyncTest", {
setUp: function () {
this.xhr = new sinon.FakeXMLHttpRequest();
this.xhr.open("GET", "/", false);
this.xhr.send();
this.xhr.setResponseHeaders({});
assert.exception(function () {
xhr.setResponseBody({});
}, "InvalidBodyException");
}
},
"should not throw": function () {
var xhr = this.xhr;
"setResponseBodySync": {
setUp: function () {
this.xhr = new sinon.FakeXMLHttpRequest();
this.xhr.open("GET", "/", false);
this.xhr.send();
this.xhr.setResponseHeaders({});
},
assertNoException(function () {
xhr.setResponseBody("");
});
},
"does not throw": function () {
var xhr = this.xhr;
"should set readyState to DONE": function () {
this.xhr.setResponseBody("");
refute.exception(function () {
xhr.setResponseBody("");
});
},
assertEquals(sinon.FakeXMLHttpRequest.DONE, this.xhr.readyState);
},
"sets readyState to DONE": function () {
this.xhr.setResponseBody("");
"should throw if responding to request twice": function () {
var xhr = this.xhr;
this.xhr.setResponseBody("");
assert.equals(this.xhr.readyState, sinon.FakeXMLHttpRequest.DONE);
},
assertException(function () {
"throws if responding to request twice": function () {
var xhr = this.xhr;
this.xhr.setResponseBody("");
assert.exception(function () {
xhr.setResponseBody("");
});
},
"does not call onreadystatechange for sync request": function () {
var xhr = new sinon.FakeXMLHttpRequest();
var spy = sinon.spy();
xhr.onreadystatechange = spy;
xhr.open("GET", "/", false);
xhr.send();
var callCount = spy.callCount;
xhr.setResponseHeaders({});
xhr.setResponseBody("");
});
},
"should not call onreadystatechange for sync request": function () {
var xhr = new sinon.FakeXMLHttpRequest();
var spy = sinon.spy();
xhr.onreadystatechange = spy;
xhr.open("GET", "/", false);
xhr.send();
var callCount = spy.callCount;
assert.equals(callCount - spy.callCount, 0);
},
xhr.setResponseHeaders({});
xhr.setResponseBody("");
"simulates synchronous request": function () {
var xhr = new sinon.FakeXMLHttpRequest();
assertEquals(0, callCount - spy.callCount);
xhr.onSend = function () {
this.setResponseHeaders({});
this.setResponseBody("Oh yeah");
};
xhr.open("GET", "/", false);
xhr.send();
assert.equals(xhr.responseText, "Oh yeah");
}
},
"should simulate synchronous request": function () {
var xhr = new sinon.FakeXMLHttpRequest();
"respond": {
setUp: function () {
this.xhr = new sinon.FakeXMLHttpRequest();
this.xhr.open("GET", "/");
var spy = this.spy = sinon.spy();
xhr.onSend = function () {
this.setResponseHeaders({});
this.setResponseBody("Oh yeah");
};
this.xhr.onreadystatechange = function () {
if (this.readyState == 4) {
spy.call(this);
}
};
xhr.open("GET", "/", false);
xhr.send();
this.xhr.send();
},
assertEquals("Oh yeah", xhr.responseText);
}
});
"calls readystate handler with readyState DONE once": function () {
this.xhr.respond(200, {}, "");
testCase("FakeXMLHttpRequestRespondTest", {
setUp: function () {
this.xhr = new sinon.FakeXMLHttpRequest();
this.xhr.open("GET", "/");
var spy = this.spy = sinon.spy();
assert.equals(this.spy.callCount, 1);
},
this.xhr.onreadystatechange = function () {
if (this.readyState == 4) {
spy.call(this);
}
};
"defaults to status 200, no headers, and blank body": function () {
this.xhr.respond();
this.xhr.send();
},
assert.equals(this.xhr.status, 200);
assert.equals(this.xhr.getAllResponseHeaders(), "");
assert.equals(this.xhr.responseText, "");
},
"should call readystate handler with readyState DONE once": function () {
this.xhr.respond(200, {}, "");
"sets status": function () {
this.xhr.respond(201);
assertEquals(1, this.spy.callCount);
},
assert.equals(this.xhr.status, 201);
},
"should default to status 200, no headers, and blank body": function () {
this.xhr.respond();
"sets status text": function () {
this.xhr.respond(201);
assertEquals(200, this.xhr.status);
assertEquals("", this.xhr.getAllResponseHeaders());
assertEquals("", this.xhr.responseText);
},
assert.equals(this.xhr.statusText, "Created");
},
"should set status": function () {
this.xhr.respond(201);
"sets headers": function () {
sinon.spy(this.xhr, "setResponseHeaders");
var responseHeaders = { some: "header", value: "over here" };
this.xhr.respond(200, responseHeaders);
assertEquals(201, this.xhr.status);
},
assert.equals(this.xhr.setResponseHeaders.args[0][0], responseHeaders);
},
"should set status text": function () {
this.xhr.respond(201);
"sets response text": function () {
this.xhr.respond(200, {}, "'tis some body text");
assertEquals("Created", this.xhr.statusText);
},
assert.equals(this.xhr.responseText, "'tis some body text");
},
"should set headers": function () {
sinon.spy(this.xhr, "setResponseHeaders");
var responseHeaders = { some: "header", value: "over here" };
this.xhr.respond(200, responseHeaders);
"completes request when onreadystatechange fails": function () {
this.xhr.onreadystatechange = sinon.stub().throws();
this.xhr.respond(200, {}, "'tis some body text");
assertEquals(responseHeaders, this.xhr.setResponseHeaders.args[0][0]);
assert.equals(this.xhr.onreadystatechange.callCount, 4);
}
},
"should set response text": function () {
this.xhr.respond(200, {}, "'tis some body text");
"getResponseHeader": {
setUp: function () {
this.xhr = new sinon.FakeXMLHttpRequest();
this.xhr.open("GET", "/");
},
assertEquals("'tis some body text", this.xhr.responseText);
},
"returns null if request is not finished": function () {
assert.isNull(this.xhr.getResponseHeader("Content-Type"));
},
"should complete request when onreadystatechange fails": function () {
this.xhr.onreadystatechange = sinon.stub().throws();
this.xhr.respond(200, {}, "'tis some body text");
"returns null if header is Set-Cookie": function () {
this.xhr.send();
assertEquals(4, this.xhr.onreadystatechange.callCount);
}
});
assert.isNull(this.xhr.getResponseHeader("Set-Cookie"));
},
testCase("FakeXMLHttpRequestGetResponseHeaderTest", {
setUp: function () {
this.xhr = new sinon.FakeXMLHttpRequest();
this.xhr.open("GET", "/");
},
"returns null if header is Set-Cookie2": function () {
this.xhr.send();
"should return null if request is not finished": function () {
assertNull(this.xhr.getResponseHeader("Content-Type"));
},
assert.isNull(this.xhr.getResponseHeader("Set-Cookie2"));
},
"should return null if header is Set-Cookie": function () {
this.xhr.send();
"returns header value": function () {
this.xhr.send();
this.xhr.setResponseHeaders({ "Content-Type": "text/html" });
assertNull(this.xhr.getResponseHeader("Set-Cookie"));
},
assert.equals(this.xhr.getResponseHeader("Content-Type"), "text/html");
},
"should return null if header is Set-Cookie2": function () {
this.xhr.send();
"returns null if header is not set": function () {
this.xhr.send();
assertNull(this.xhr.getResponseHeader("Set-Cookie2"));
},
assert.isNull(this.xhr.getResponseHeader("Content-Type"));
},
"should return header value": function () {
this.xhr.send();
this.xhr.setResponseHeaders({ "Content-Type": "text/html" });
"returns headers case insensitive": function () {
this.xhr.send();
this.xhr.setResponseHeaders({ "Content-Type": "text/html" });
assertEquals("text/html", this.xhr.getResponseHeader("Content-Type"));
assert.equals(this.xhr.getResponseHeader("content-type"), "text/html");
}
},
"should return null if header is not set": function () {
this.xhr.send();
"getAllResponseHeaders": {
setUp: function () {
this.xhr = new sinon.FakeXMLHttpRequest();
this.xhr.open("GET", "/");
},
assertNull(this.xhr.getResponseHeader("Content-Type"));
},
"returns empty string if request is not finished": function () {
assert.equals(this.xhr.getAllResponseHeaders(), "");
},
"should return headers case insensitive": function () {
this.xhr.send();
this.xhr.setResponseHeaders({ "Content-Type": "text/html" });
"does not return Set-Cookie and Set-Cookie2 headers": function () {
this.xhr.send();
this.xhr.setResponseHeaders({
"Set-Cookie": "Hey",
"Set-Cookie2": "There"
});
assertEquals("text/html", this.xhr.getResponseHeader("content-type"));
}
});
assert.equals(this.xhr.getAllResponseHeaders(), "");
},
testCase("FakeXMLHttpRequestGetAllResponseHeadersTest", {
setUp: function () {
this.xhr = new sinon.FakeXMLHttpRequest();
this.xhr.open("GET", "/");
},
"returns headers": function () {
this.xhr.send();
this.xhr.setResponseHeaders({
"Content-Type": "text/html",
"Set-Cookie2": "There",
"Content-Length": "32"
});
"should return empty string if request is not finished": function () {
assertEquals("", this.xhr.getAllResponseHeaders());
assert.equals(this.xhr.getAllResponseHeaders(), "Content-Type: text/html\r\nContent-Length: 32\r\n");
}
},
"should not return Set-Cookie and Set-Cookie2 headers": function () {
this.xhr.send();
this.xhr.setResponseHeaders({
"Set-Cookie": "Hey",
"Set-Cookie2": "There"
});
"abort": {
setUp: function () {
this.xhr = new sinon.FakeXMLHttpRequest();
},
assertEquals("", this.xhr.getAllResponseHeaders());
},
"sets aborted flag to true": function () {
this.xhr.aborted = true;
"should return headers": function () {
this.xhr.send();
this.xhr.setResponseHeaders({
"Content-Type": "text/html",
"Set-Cookie2": "There",
"Content-Length": "32"
});
this.xhr.abort();
assertEquals("Content-Type: text/html\r\nContent-Length: 32\r\n", this.xhr.getAllResponseHeaders());
}
});
assert.isTrue(this.xhr.aborted);
},
testCase("FakeXMLHttpRequestAbortTest", {
setUp: function () {
this.xhr = new sinon.FakeXMLHttpRequest();
},
"sets responseText to null": function () {
this.xhr.responseText = "Partial data";
"should set aborted flag to true": function () {
this.xhr.aborted = true;
this.xhr.abort();
this.xhr.abort();
assert.isNull(this.xhr.responseText);
},
assertTrue(this.xhr.aborted);
},
"sets errorFlag to true": function () {
this.xhr.errorFlag = true;
"should set responseText to null": function () {
this.xhr.responseText = "Partial data";
this.xhr.abort();
this.xhr.abort();
assert.isTrue(this.xhr.errorFlag);
},
assertNull(this.xhr.responseText);
},
"nulls request headers": function () {
this.xhr.open("GET", "/");
this.xhr.setRequestHeader("X-Test", "Sumptn");
"should set errorFlag to true": function () {
this.xhr.errorFlag = true;
this.xhr.abort();
this.xhr.abort();
assert.equals(this.xhr.requestHeaders, {});
},
assertTrue(this.xhr.errorFlag);
},
"sets state to DONE if sent before": function () {
var readyState;
this.xhr.open("GET", "/");
this.xhr.send();
"should null request headers": function () {
this.xhr.open("GET", "/");
this.xhr.setRequestHeader("X-Test", "Sumptn");
this.xhr.onreadystatechange = function () {
readyState = this.readyState;
};
this.xhr.abort();
this.xhr.abort();
assertEquals({}, this.xhr.requestHeaders);
},
assert.equals(readyState, sinon.FakeXMLHttpRequest.DONE);
},
"should set state to DONE if sent before": function () {
var readyState;
this.xhr.open("GET", "/");
this.xhr.send();
"sets send flag to false if sent before": function () {
this.xhr.open("GET", "/");
this.xhr.send();
this.xhr.onreadystatechange = function () {
readyState = this.readyState;
};
this.xhr.abort();
this.xhr.abort();
assert.isFalse(this.xhr.sendFlag);
},
assertEquals(sinon.FakeXMLHttpRequest.DONE, readyState);
},
"dispatches readystatechange event if sent before": function () {
this.xhr.open("GET", "/");
this.xhr.send();
this.xhr.onreadystatechange = sinon.stub();
"should set send flag to false if sent before": function () {
this.xhr.open("GET", "/");
this.xhr.send();
this.xhr.abort();
this.xhr.abort();
assert(this.xhr.onreadystatechange.called);
},
assertFalse(this.xhr.sendFlag);
},
"sets readyState to unsent if sent before": function () {
this.xhr.open("GET", "/");
this.xhr.send();
"should dispatch readystatechange event if sent before": function () {
this.xhr.open("GET", "/");
this.xhr.send();
this.xhr.onreadystatechange = sinon.stub();
this.xhr.abort();
this.xhr.abort();
assert.equals(this.xhr.readyState, sinon.FakeXMLHttpRequest.UNSENT);
},
assert(this.xhr.onreadystatechange.called);
},
"does not dispatch readystatechange event if readyState is unsent": function () {
this.xhr.onreadystatechange = sinon.stub();
"should set readyState to unsent if sent before": function () {
this.xhr.open("GET", "/");
this.xhr.send();
this.xhr.abort();
this.xhr.abort();
assert.isFalse(this.xhr.onreadystatechange.called);
},
assertEquals(sinon.FakeXMLHttpRequest.UNSENT, this.xhr.readyState);
"does not dispatch readystatechange event if readyState is opened but not sent": function () {
this.xhr.open("GET", "/");
this.xhr.onreadystatechange = sinon.stub();
this.xhr.abort();
assert.isFalse(this.xhr.onreadystatechange.called);
}
},
"should not dispatch readystatechange event if readyState is unsent": function () {
this.xhr.onreadystatechange = sinon.stub();
"responseXML": {
setUp: function () {
this.xhr = new sinon.FakeXMLHttpRequest();
this.xhr.open("GET", "/");
},
this.xhr.abort();
"is initially null": function () {
assert.isNull(this.xhr.responseXML);
},
assertFalse(this.xhr.onreadystatechange.called);
},
"is null when the response body is empty": function () {
this.xhr.send();
"should not dispatch readystatechange event if readyState is opened but not sent": function () {
this.xhr.open("GET", "/");
this.xhr.onreadystatechange = sinon.stub();
this.xhr.respond(200, {}, "");
this.xhr.abort();
assert.isNull(this.xhr.responseXML);
},
assertFalse(this.xhr.onreadystatechange.called);
}
});
"parses XML for application/xml": function () {
this.xhr.send();
testCase("FakeXMLHttpRequestResponseXMLTest", {
setUp: function () {
this.xhr = new sinon.FakeXMLHttpRequest();
this.xhr.open("GET", "/");
},
this.xhr.respond(200, { "Content-Type": "application/xml" },
"<div><h1>Hola!</h1></div>");
"should initially be null": function () {
assertNull(this.xhr.responseXML);
},
var doc = this.xhr.responseXML;
var elements = doc.documentElement.getElementsByTagName("h1");
assert.equals(elements.length, 1);
assert.equals(elements[0].tagName, "h1");
},
"should be null when the response body is empty": function () {
this.xhr.send();
"parses XML for text/xml": function () {
this.xhr.send();
this.xhr.respond(200, {}, "");
this.xhr.respond(200, { "Content-Type": "text/xml" },
"<div><h1>Hola!</h1></div>");
assertNull(this.xhr.responseXML);
},
refute.isNull(this.xhr.responseXML);
},
"should parse XML for application/xml": function () {
this.xhr.send();
"parses XML for custom xml content type": function () {
this.xhr.send();
this.xhr.respond(200, { "Content-Type": "application/xml" },
"<div><h1>Hola!</h1></div>");
this.xhr.respond(200, { "Content-Type": "application/text+xml" },
"<div><h1>Hola!</h1></div>");
var doc = this.xhr.responseXML;
var elements = doc.documentElement.getElementsByTagName("h1");
assertEquals(1, elements.length);
assertEquals("h1", elements[0].tagName);
},
refute.isNull(this.xhr.responseXML);
},
"should parse XML for text/xml": function () {
this.xhr.send();
"parses XML with no Content-Type": function () {
this.xhr.send();
this.xhr.respond(200, { "Content-Type": "text/xml" },
"<div><h1>Hola!</h1></div>");
this.xhr.respond(200, {}, "<div><h1>Hola!</h1></div>");
assertNotNull(this.xhr.responseXML);
},
var doc = this.xhr.responseXML;
var elements = doc.documentElement.getElementsByTagName("h1");
assert.equals(elements.length, 1);
assert.equals(elements[0].tagName, "h1");
},
"should parse XML for custom xml content type": function () {
this.xhr.send();
"does not parse XML with Content-Type text/plain": function () {
this.xhr.send();
this.xhr.respond(200, { "Content-Type": "application/text+xml" },
"<div><h1>Hola!</h1></div>");
this.xhr.respond(200, { "Content-Type": "text/plain" }, "<div></div>");
assertNotNull(this.xhr.responseXML);
assert.isNull(this.xhr.responseXML);
}
},
"should parse XML with no Content-Type": function () {
this.xhr.send();
"stub XHR": {
setUp: fakeXhrSetUp,
tearDown: fakeXhrTearDown,
this.xhr.respond(200, {}, "<div><h1>Hola!</h1></div>");
"returns FakeXMLHttpRequest constructor": function () {
assert.same(this.fakeXhr, sinon.FakeXMLHttpRequest);
},
var doc = this.xhr.responseXML;
var elements = doc.documentElement.getElementsByTagName("h1");
assertEquals(1, elements.length);
assertEquals("h1", elements[0].tagName);
},
"temporarily blesses FakeXMLHttpRequest with restore method": function () {
assert.isFunction(this.fakeXhr.restore);
},
"should not parse XML with Content-Type text/plain": function () {
this.xhr.send();
"calling restore removes temporary method": function () {
this.fakeXhr.restore();
this.xhr.respond(200, { "Content-Type": "text/plain" }, "<div></div>");
refute.defined(this.fakeXhr.restore);
},
assertNull(this.xhr.responseXML);
}
});
"removes XMLHttpRequest onCreate listener": function () {
sinon.FakeXMLHttpRequest.onCreate = function () {};
var globalXMLHttpRequest = global.XMLHttpRequest;
var globalActiveXObject = global.ActiveXObject;
this.fakeXhr.restore();
var fakeXhrSetUp = function () {
this.fakeXhr = sinon.useFakeXMLHttpRequest();
};
refute.defined(sinon.FakeXMLHttpRequest.onCreate);
},
var fakeXhrTearDown = function () {
if (typeof this.fakeXhr.restore == "function") {
this.fakeXhr.restore();
}
};
"optionally keeps XMLHttpRequest onCreate listener": function () {
var onCreate = function () {};
sinon.FakeXMLHttpRequest.onCreate = onCreate;
testCase("StubXHRTest", {
setUp: fakeXhrSetUp,
tearDown: fakeXhrTearDown,
this.fakeXhr.restore(true);
"should return FakeXMLHttpRequest constructor": function () {
assertSame(sinon.FakeXMLHttpRequest, this.fakeXhr);
assert.same(sinon.FakeXMLHttpRequest.onCreate, onCreate);
}
},
"filtering": {
setUp: function () {
sinon.FakeXMLHttpRequest.useFilters = true;
sinon.FakeXMLHttpRequest.filters = [];
sinon.useFakeXMLHttpRequest();
},
"should temporarily bless FakeXMLHttpRequest with restore method": function () {
assertFunction(this.fakeXhr.restore);
},
tearDown: function () {
sinon.FakeXMLHttpRequest.useFilters = false;
sinon.FakeXMLHttpRequest.restore();
if (sinon.FakeXMLHttpRequest.defake.restore) {
sinon.FakeXMLHttpRequest.defake.restore();
}
},
"calling restore should remove temporary method": function () {
this.fakeXhr.restore();
"does not defake XHR requests that don't match a filter": function () {
sinon.stub(sinon.FakeXMLHttpRequest, "defake");
assertUndefined(this.fakeXhr.restore);
},
sinon.FakeXMLHttpRequest.addFilter(function () { return false; });
new XMLHttpRequest().open("GET", "http://example.com");
"should remove XMLHttpRequest onCreate listener": function () {
sinon.FakeXMLHttpRequest.onCreate = function () {};
refute(sinon.FakeXMLHttpRequest.defake.called);
},
this.fakeXhr.restore();
"defakes XHR requests that match a filter": function () {
sinon.stub(sinon.FakeXMLHttpRequest, "defake");
assertUndefined(sinon.FakeXMLHttpRequest.onCreate);
sinon.FakeXMLHttpRequest.addFilter(function () { return true; });
new XMLHttpRequest().open("GET", "http://example.com");
assert(sinon.FakeXMLHttpRequest.defake.calledOnce);
}
},
"should optionally keep XMLHttpRequest onCreate listener": function () {
var onCreate = function () {};
sinon.FakeXMLHttpRequest.onCreate = onCreate;
"defaked XHR": {
setUp: function () {
this.fakeXhr = new sinon.FakeXMLHttpRequest();
},
this.fakeXhr.restore(true);
"updates attributes from working XHR object when ready state changes": function () {
var workingXHRInstance;
var readyStateCb;
var workingXHROverride = function () {
workingXHRInstance = this;
this.addEventListener = function (str, fn) {
readyStateCb = fn;
};
this.open = function () {};
};
var fakeXhr = this.fakeXhr;
runWithWorkingXHROveride(workingXHROverride, function () {
sinon.FakeXMLHttpRequest.defake(fakeXhr, []);
workingXHRInstance.statusText = "This is the status text of the real XHR";
workingXHRInstance.readyState = 4;
readyStateCb();
assert.equals(fakeXhr.statusText, "This is the status text of the real XHR");
});
},
assertSame(onCreate, sinon.FakeXMLHttpRequest.onCreate);
}
});
testCase("XHRFiltering",{
setUp: function() {
sinon.FakeXMLHttpRequest.useFilters = true;
sinon.FakeXMLHttpRequest.filters = [];
sinon.useFakeXMLHttpRequest();
},
tearDown: function() {
sinon.FakeXMLHttpRequest.useFilters = false;
sinon.FakeXMLHttpRequest.restore();
},
"should not defake XHR requests that don't match a filter": function() {
var mock = sinon.mock(sinon.FakeXMLHttpRequest)
try {
mock.expects("defake").never()
sinon.FakeXMLHttpRequest.addFilter(function() { return false });
new XMLHttpRequest().open("GET","http://example.com");
} finally { mock.verify(); }
},
"should defake XHR requests that match a filter": function() {
var mock = sinon.mock(sinon.FakeXMLHttpRequest)
try {
mock.expects("defake").once()
sinon.FakeXMLHttpRequest.addFilter(function() { return true });
new XMLHttpRequest().open("GET","http://example.com");
} finally { mock.verify(); }
}
});
var runWithWorkingXHROveride = function(workingXHR,test) {
try {
var original = sinon.xhr.workingXHR;
sinon.xhr.workingXHR = workingXHR;
test();
} finally {
sinon.xhr.workingXHR = original;
}
};
var fakeXhr;
testCase("DefakedXHR",{
setUp: function() {
fakeXhr = new sinon.FakeXMLHttpRequest();
},
"should update attributes from working XHR object when ready state changes": function() {
var workingXHRInstance;
var readyStateCb;
var workingXHROverride = function() {
workingXHRInstance = this;
this.addEventListener = function(str,fn) {
readyStateCb = fn;
"passes on methods to working XHR object": function () {
var workingXHRInstance;
var spy;
var workingXHROverride = function () {
workingXHRInstance = this;
this.addEventListener = this.open = function () {};
};
this.open = function() {};
};
runWithWorkingXHROveride(workingXHROverride,function() {
sinon.FakeXMLHttpRequest.defake(fakeXhr,[]);
workingXHRInstance.statusText = "This is the status text of the real XHR";
workingXHRInstance.readyState = 4;
readyStateCb();
assertEquals(
"This is the status text of the real XHR",
fakeXhr.statusText
);
});
},
"should pass on methods to working XHR object": function() {
var workingXHRInstance;
var spy;
var workingXHROverride = function() {
workingXHRInstance = this;
this.addEventListener = this.open = function() {};
};
runWithWorkingXHROveride(workingXHROverride,function() {
sinon.FakeXMLHttpRequest.defake(fakeXhr,[]);
workingXHRInstance.getResponseHeader = spy = sinon.spy();
fakeXhr.getResponseHeader();
sinon.assert.calledOnce(spy);
});
},
"should call leagacy onreadystatechange handlers": function() {
var workingXHRInstance;
var spy;
var readyStateCb;
var workingXHROverride = function() {
workingXHRInstance = this;
this.addEventListener = function(str,fn) {
readyStateCb = fn;
var fakeXhr = this.fakeXhr;
runWithWorkingXHROveride(workingXHROverride, function () {
sinon.FakeXMLHttpRequest.defake(fakeXhr, []);
workingXHRInstance.getResponseHeader = spy = sinon.spy();
fakeXhr.getResponseHeader();
assert(spy.calledOnce);
});
},
"calls legacy onreadystatechange handlers": function () {
var workingXHRInstance;
var spy;
var readyStateCb;
var workingXHROverride = function () {
workingXHRInstance = this;
this.addEventListener = function (str, fn) {
readyStateCb = fn;
};
this.open = function () {};
};
this.open = function() {};
};
runWithWorkingXHROveride(workingXHROverride,function() {
sinon.FakeXMLHttpRequest.defake(fakeXhr,[]);
fakeXhr.onreadystatechange = spy = sinon.spy()
readyStateCb();
sinon.assert.calledOnce(spy);
});
var fakeXhr = this.fakeXhr;
runWithWorkingXHROveride(workingXHROverride, function () {
sinon.FakeXMLHttpRequest.defake(fakeXhr, []);
fakeXhr.onreadystatechange = spy = sinon.spy();
readyStateCb();
assert(spy.calledOnce);
});
},
"performs initial readystatechange on opening when filters are being used, but don't match": function () {
try {
sinon.FakeXMLHttpRequest.useFilters = true;
var spy = sinon.spy();
this.fakeXhr.addEventListener("readystatechange", spy);
this.fakeXhr.open("GET","http://example.com", true);
assert(spy.calledOnce);
} finally {
sinon.FakeXMLHttpRequest.useFilters = false;
}
}
},
"should perform initial readystatechange on opening when filters are being used, but don't match": function() {
try {
sinon.FakeXMLHttpRequest.useFilters = true;
var spy = sinon.spy();
fakeXhr.addEventListener("readystatechange",spy);
fakeXhr.open("GET","http://example.com",true);
sinon.assert.calledOnce(spy);
} finally {
sinon.FakeXMLHttpRequest.useFilters = false;
}
}
});
AsyncTestCase("DefakedXHRTest",{
setUp: function() {
sinon.FakeXMLHttpRequest.useFilters = true;
sinon.FakeXMLHttpRequest.filters = [];
sinon.useFakeXMLHttpRequest();
sinon.FakeXMLHttpRequest.addFilter(function() {return true;});
},
tearDown: function() {
sinon.FakeXMLHttpRequest.useFilters = false;
sinon.FakeXMLHttpRequest.filters = [];
sinon.FakeXMLHttpRequest.restore();
},
"test loads resource asynchronously": function(q) {
q.call(function(callbacks) {
var req = new XMLHttpRequest;
var responseReceived = callbacks.add(function(responseText) {
assertMatch(/loaded successfully/, responseText);
});
req.onreadystatechange = function() {
if(this.readyState == 4) {
responseReceived(this.responseText);
"defaked XHR filters": {
setUp: function () {
sinon.FakeXMLHttpRequest.useFilters = true;
sinon.FakeXMLHttpRequest.filters = [];
sinon.useFakeXMLHttpRequest();
sinon.FakeXMLHttpRequest.addFilter(function () { return true; });
},
tearDown: function () {
sinon.FakeXMLHttpRequest.useFilters = false;
sinon.FakeXMLHttpRequest.filters = [];
sinon.FakeXMLHttpRequest.restore();
},
"loads resource asynchronously": function (done) {
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (this.readyState == 4) {
assert.match(this.responseText, /loaded successfully/);
done();
}
};
setTimeout(callbacks.addErrback("timeout on ajax"),1000);
req.open("GET", "/test/resources/xhr_target.txt", true);
req.send();
},
req.open("GET","/test/test/resources/xhr_target.txt",true);
"loads resource synchronously": function () {
var req = new XMLHttpRequest();
req.open("GET", "/test/resources/xhr_target.txt", false);
req.send();
});
assert.match(req.responseText, /loaded successfully/);
}
},
"test loads resource synchronously": function() {
var req = new XMLHttpRequest;
req.open("GET","/test/test/resources/xhr_target.txt",false);
req.send();
assertMatch(/loaded successfully/, req.responseText);
}
});
if (typeof ActiveXObject == "undefined") {
testCase("StubXHRActiveXTest", {
"missing ActiveXObject": {
requiresSupportFor: {
"no ActiveXObject": typeof ActiveXObject === "undefined"
},
setUp: fakeXhrSetUp,
tearDown: fakeXhrTearDown,
"should notify user of missing ActiveXObject": function () {
jstestdriver.console.log("Environment does not support ActiveXObject");
"does not expose ActiveXObject": function () {
assert.equals(typeof ActiveXObject, "undefined");
},
"should not expose ActiveXObject": function () {
assertEquals("undefined", typeof ActiveXObject);
},
"should not expose ActiveXObject when restored": function () {
"does not expose ActiveXObject when restored": function () {
this.fakeXhr.restore();
assertEquals("undefined", typeof ActiveXObject);
assert.equals(typeof ActiveXObject, "undefined");
}
});
} else {
testCase("StubXHRActiveXTest", {
},
"native ActiveXObject": {
requiresSupportFor: {
"ActiveXObject": typeof ActiveXObject !== "undefined"
},
setUp: fakeXhrSetUp,
tearDown: fakeXhrTearDown,
"should hijack ActiveXObject": function () {
assertNotSame(globalActiveXObject, global.ActiveXObject);
assertNotSame(globalActiveXObject, window.ActiveXObject);
assertNotSame(globalActiveXObject, ActiveXObject);
"hijacks ActiveXObject": function () {
refute.same(global.ActiveXObject, globalActiveXObject);
refute.same(window.ActiveXObject, globalActiveXObject);
refute.same(ActiveXObject, globalActiveXObject);
},
"should restore global ActiveXObject": function () {
"restores global ActiveXObject": function () {
this.fakeXhr.restore();
assertSame(globalActiveXObject, global.ActiveXObject);
assertSame(globalActiveXObject, window.ActiveXObject);
assertSame(globalActiveXObject, ActiveXObject);
assert.same(global.ActiveXObject, globalActiveXObject);
assert.same(window.ActiveXObject, globalActiveXObject);
assert.same(ActiveXObject, globalActiveXObject);
},
"should create FakeXHR object with ActiveX Microsoft.XMLHTTP": function () {
"creates FakeXHR object with ActiveX Microsoft.XMLHTTP": function () {
var xhr = new ActiveXObject("Microsoft.XMLHTTP");

@@ -1147,3 +1138,3 @@

"should create FakeXHR object with ActiveX Msxml2.XMLHTTP": function () {
"creates FakeXHR object with ActiveX Msxml2.XMLHTTP": function () {
var xhr = new ActiveXObject("Msxml2.XMLHTTP");

@@ -1154,3 +1145,3 @@

"should create FakeXHR object with ActiveX Msxml2.XMLHTTP.3.0": function () {
"creates FakeXHR object with ActiveX Msxml2.XMLHTTP.3.0": function () {
var xhr = new ActiveXObject("Msxml2.XMLHTTP.3.0");

@@ -1161,3 +1152,3 @@

"should create FakeXHR object with ActiveX Msxml2.XMLHTTP.6.0": function () {
"creates FakeXHR object with ActiveX Msxml2.XMLHTTP.6.0": function () {
var xhr = new ActiveXObject("Msxml2.XMLHTTP.6.0");

@@ -1167,41 +1158,37 @@

}
});
}
},
if (typeof XMLHttpRequest == "undefined") {
testCase("StubXHRNativeTest", {
"missing native XHR": {
requiresSupportFor: { "no native XHR": typeof XMLHttpRequest == "undefined" },
setUp: fakeXhrSetUp,
tearDown: fakeXhrTearDown,
"should notify user of missing XMLHttpRequest": function () {
jstestdriver.console.log("Environment does not support XMLHttpRequest");
"does not expose XMLHttpRequest": function () {
assert.equals(typeof XMLHttpRequest, "undefined");
},
"should not expose XMLHttpRequest": function () {
assertEquals("undefined", typeof XMLHttpRequest);
},
"should not expose XMLHttpRequest after restore": function () {
"does not expose XMLHttpRequest after restore": function () {
this.fakeXhr.restore();
assertEquals("undefined", typeof XMLHttpRequest);
assert.equals(typeof XMLHttpRequest, "undefined");
}
});
} else {
testCase("StubXHRNativeTest", {
},
"native XHR": {
requiresSupportFor: { "XHR": typeof XMLHttpRequest !== "undefined" },
setUp: fakeXhrSetUp,
tearDown: fakeXhrTearDown,
"should replace global XMLHttpRequest": function () {
assertNotSame(globalXMLHttpRequest, XMLHttpRequest);
assertSame(sinon.FakeXMLHttpRequest, XMLHttpRequest);
"replaces global XMLHttpRequest": function () {
refute.same(XMLHttpRequest, globalXMLHttpRequest);
assert.same(XMLHttpRequest, sinon.FakeXMLHttpRequest);
},
"should restore global XMLHttpRequest": function () {
"restores global XMLHttpRequest": function () {
this.fakeXhr.restore();
assertSame(globalXMLHttpRequest, XMLHttpRequest);
assert.same(XMLHttpRequest, globalXMLHttpRequest);
}
});
}
}
});
}(this));

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

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