A test spy is a function that records arguments, return value, the value of this and exception thrown (if any) for all its calls. There are two types of spies: Some are anonymous functions, while others wrap methods that already exist in the system under test.
When the behavior of the spied-on function is not under test, you can use an anonymous function spy. The spy won’t do anything except record information about its calls. A common use case for this type of spy is testing how a function handles a callback, as in the following simplified example:
"test should call subscribers on publish": function () {
var callback = sinon.spy();
PubSub.subscribe("message", callback);
PubSub.publishSync("message");
assertTrue(callback.called);
}
sinon.spy(object, "method") creates a spy that wraps the existing function object.method. The spy will behave exactly like the original method (including when used as a constructor), but you will have access to data about all calls. The following is a slightly contrived example:
{
setUp: function () {
sinon.spy(jQuery, "ajax");
},
tearDown: function () {
jQuery.ajax.restore(); // Unwraps the spy
},
"test should inspect jQuery.getJSON's usage of jQuery.ajax": function () {
jQuery.getJSON("/some/resource");
assert(jQuery.ajax.calledOnce);
assertEquals("/some/resource", jQuery.ajax.getCall(0).args[0].url);
assertEquals("json", jQuery.ajax.getCall(0).args[0].dataType);
}
}
sinon.spy() Method Signaturesvar spy = sinon.spy();this value, exceptions and return values for all calls. var spy = sinon.spy(myFunc);var spy = sinon.spy(object, "method");object.method and replaces the original method with the spy. An exception is thrown if the property is not already a function. The spy acts exactly like the original method in all cases. The original method can be restored by calling object.method.restore(). The returned spy is the function object which replaced the original method. spy === object.method. Spies provide a rich interface to inspect their usage. The above examples showed the calledOnce boolean property as well as the getCall method and the returned object’s args property. There are three ways of inspecting call data.
The preferred approach is to use the spy’s calledWith method (and friends) because it keeps your test from being too specific about which call did what and so on. It will return true if the spy was ever called with the provided arguments.
"test should call subscribers with message as first argument" : function () {
var message = 'an example message';
var spy = sinon.spy();
PubSub.subscribe(message, spy);
PubSub.publishSync(message, "some payload");
assert(spy.calledWith(message));
}
If you want to be specific, you can directly check the first argument of the first call. There are two ways of achieving this:
"test should call subscribers with message as first argument" : function () {
var message = 'an example message';
var spy = sinon.spy();
PubSub.subscribe(message, spy);
PubSub.publishSync(message, "some payload");
assertEquals(message, spy.args[0][0]);
}
"test should call subscribers with message as first argument" : function () {
var message = 'an example message';
var spy = sinon.spy();
PubSub.subscribe(message, spy);
PubSub.publishSync(message, "some payload");
assertEquals(message, spy.getCall(0).args[0]);
}
The first example uses the two-dimensional args array directly on the spy, while the second example fetches the first call object and then accesses its args array. Which one to use is a matter of preference, but the recommended approach is going with spy.calledWith(arg1, arg2, ...) unless there’s a need to make the tests highly specific.
Spy objects are objects returned from sinon.spy(). When spying on existing methods with sinon.spy(object, method), the following properties and methods are also available on object.method.
spy.withArgs(arg1[, arg2, ...]);Creates a spy that only records calls when the received arguments match those passed to withArgs. This is useful to be more expressive in your assertions, where you can access the spy with the same call.
"should call method once with each argument": function () {
var object = { method: function () {} };
var spy = sinon.spy(object, "method");
object.method(42);
object.method(1);
assert(spy.withArgs(42).calledOnce);
assert(spy.withArgs(1).calledOnce);
}
spy.callCountThe number of recorded calls.
spy.calledtrue if the spy was called at least once
spy.notCalledtrue if the spy was not called
spy.calledOncetrue if spy was called exactly once
spy.calledTwicetrue if the spy was called exactly twice
spy.calledThricetrue if the spy was called exactly thrice
spy.firstCallThe first call
spy.secondCallThe second call
spy.thirdCallThe third call
spy.lastCallThe last call
spy.calledBefore(anotherSpy);Returns true if the spy was called before anotherSpy
spy.calledAfter(anotherSpy);Returns true if the spy was called after anotherSpy
spy.calledImmediatelyBefore(anotherSpy);Returns true if spy was called before anotherSpy, and no spy calls occurred between spy and anotherSpy.
spy.calledImmediatelyAfter(anotherSpy);Returns true if spy was called after anotherSpy, and no spy calls occurred between anotherSpy and spy.
spy.calledOn(obj);Returns true if the spy was called at least once with obj as this. calledOn also accepts a matcher spyCall.calledOn(sinon.match(fn)) (see matchers).
spy.alwaysCalledOn(obj);Returns true if the spy was always called with obj as this.
spy.calledWith(arg1, arg2, ...);Returns true if spy was called at least once with the provided arguments.
Can be used for partial matching, Sinon only checks the provided arguments against actual arguments, so a call that received the provided arguments (in the same spots) and possibly others as well will return true.
spy.calledOnceWith(arg1, arg2, ...);Returns true if spy was called at exactly once with the provided arguments.
spy.alwaysCalledWith(arg1, arg2, ...);Returns true if spy was always called with the provided arguments (and possibly others).
spy.calledWithExactly(arg1, arg2, ...);Returns true if spy was called at least once with the provided arguments and no others.
spy.calledOnceWithExactly(arg1, arg2, ...);Returns true if spy was called exactly once and with only the provided arguments.
spy.alwaysCalledWithExactly(arg1, arg2, ...);Returns true if spy was always called with the exact provided arguments.
spy.calledWithMatch(arg1, arg2, ...);Returns true if spy was called with matching arguments (and possibly others).
This behaves the same as spy.calledWith(sinon.match(arg1), sinon.match(arg2), ...).
spy.alwaysCalledWithMatch(arg1, arg2, ...);Returns true if spy was always called with matching arguments (and possibly others).
This behaves the same as spy.alwaysCalledWith(sinon.match(arg1), sinon.match(arg2), ...).
spy.calledWithNew();Returns true if spy/stub was called the new operator.
Beware that this is inferred based on the value of the this object and the spy function’s prototype, so it may give false positives if you actively return the right kind of object.
spy.neverCalledWith(arg1, arg2, ...);Returns true if the spy/stub was never called with the provided arguments.
spy.neverCalledWithMatch(arg1, arg2, ...);Returns true if the spy/stub was never called with matching arguments.
This behaves the same as spy.neverCalledWith(sinon.match(arg1), sinon.match(arg2), ...).
spy.threw();Returns true if spy threw an exception at least once.
spy.threw("TypeError");Returns true if spy threw an exception of the provided type at least once.
spy.threw(obj);Returns true if spy threw the provided exception object at least once.
spy.alwaysThrew();Returns true if spy always threw an exception.
spy.alwaysThrew("TypeError");Returns true if spy always threw an exception of the provided type.
spy.alwaysThrew(obj);Returns true if spy always threw the provided exception object.
spy.returned(obj);Returns true if spy returned the provided value at least once.
Uses deep comparison for objects and arrays. Use spy.returned(sinon.match.same(obj)) for strict comparison (see matchers).
spy.alwaysReturned(obj);Returns true if spy always returned the provided value.
var spyCall = spy.getCall(n);Returns the nth call.
Accessing individual calls helps with more detailed behavior verification when the spy is called more than once.
sinon.spy(jQuery, "ajax");
jQuery.ajax("/stuffs");
var spyCall = jQuery.ajax.getCall(0);
assertEquals("/stuffs", spyCall.args[0]);
var spyCalls = spy.getCalls();Returns an Array of all calls recorded by the spy.
spy.thisValuesArray of this objects, spy.thisValues[0] is the this object for the first call.
spy.argsArray of arguments received, spy.args[0] is an array of arguments received in the first call.
spy.exceptionsArray of exception objects thrown, spy.exceptions[0] is the exception thrown by the first call.
If the call did not throw an error, the value at the call’s location in .exceptions will be undefined.
spy.returnValuesArray of return values, spy.returnValues[0] is the return value of the first call.
If the call did not explicitly return a value, the value at the call’s location in .returnValues will be undefined.
spy.resetHistory();Resets the state of a spy.
spy.restore();Replaces the spy with the original method. Only available if the spy replaced an existing method.
spy.printf("format string", [arg1, arg2, ...]);Returns the passed format string with the following replacements performed:
%n%c%C%tthis values the spy was called on%nprintf
%*printf
%D
© 2010–2018 Christian Johansen
Licensed under the BSD License.
https://sinonjs.org/releases/v7.1.1/spies