Skip to content

Instantly share code, notes, and snippets.

@DylanKojiCheslin
Forked from yoavniran/ultimate-ut-cheat-sheet.md
Last active December 27, 2023 14:00
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save DylanKojiCheslin/2744ece75083cdafede952c2b351ce39 to your computer and use it in GitHub Desktop.
Save DylanKojiCheslin/2744ece75083cdafede952c2b351ce39 to your computer and use it in GitHub Desktop.
a Sinon Unit Testing Cheat-sheet

The Non-Ultimate Sinon Cheat-sheet

forked from GitHub Much thanks to yoavniran!


## Sinon

links: sinon home , docs , code

Spy

	var spy = sinon.spy();

Creates an anonymous function that records arguments, this value, exceptions and return values for all calls.

	var spy = sinon.spy(myFunc);

Spies on the provided function

	var spy = sinon.spy(object, "method");

Creates a spy for object.method and replaces the original method with the spy. 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.

Spy method Description
spy.callCount The number of recorded calls.
spy.called true if the spy was called at least once
spy.calledOnce true if spy was called exactly once
spy.calledTwice true if the spy was called exactly twice
spy.calledThrice true if the spy was called exactly thrice
spy.firstCall The first call
spy.secondCall The second call
spy.thirdCall The third call
spy.lastCall The 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.calledOn(obj); Returns true if the spy was called at least once with obj as this
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.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.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. Example:

sinon.spy(jQuery, "ajax");
jQuery.ajax("/stuffs");
var spyCall = jQuery.ajax.getCall(0);
assertEquals("/stuffs", spyCall.args[0]);
spy.thisValues Array of this objects, spy.thisValues[0] is the this object for the first call.
spy.args Array of arguments received, spy.args[0] is an array of arguments received in the first call.
spy.exceptions Array 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.returnValues Array 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.reset() Resets the state of a spy.
spy.printf(format string", [arg1, arg2, ...])` Returns the passed format string with the following replacements performed:


  • %n: the name of the spy (“spy” by default)
  • %c: the number of times the spy was called, in words (“once”, “twice”, etc.)
  • %C: a list of string representations of the calls to the spy, with each call prefixed by a newline and four spaces
  • %t: a comma-delimited list of this values the spy was called on
  • %n: the formatted value of the nth argument passed to printf
  • %*: a comma-delimited list of the (non-format string) arguments passed to printf
#### Individual spy calls
Spy method Description
var spyCall = spy.getCall(n) Returns the nth [call](#spycall). Accessing individual calls helps with more detailed behavior verification when the spy is called more than once. Example:
spyCall.calledOn(obj); Returns true if obj was this for this call.
spyCall.calledWith(arg1, arg2, ...); Returns true if call received provided arguments (and possibly others).
spyCall.calledWithExactly(arg1, arg2, ...); Returns true if call received provided arguments and no others.
spyCall.calledWithMatch(arg1, arg2, ...); Returns true if call received matching arguments (and possibly others). This behaves the same as spyCall.calledWith(sinon.match(arg1), sinon.match(arg2), ...).
spyCall.notCalledWith(arg1, arg2, ...); Returns true if call did not receive provided arguments.
spyCall.notCalledWithMatch(arg1, arg2, ...); Returns true if call did not receive matching arguments. This behaves the same as spyCall.notCalledWith(sinon.match(arg1), sinon.match(arg2), ...).
spyCall.threw(); Returns true if call threw an exception.
spyCall.threw(TypeError"); Returns true if call threw exception of provided type.
spyCall.threw(obj); Returns true if call threw provided exception object.
spyCall.thisValue The call’s this value.
spyCall.args Array of received arguments.
spyCall.exception Exception thrown, if any.
spyCall.returnValue Return value.

link: stubs doc

	var stub = sinon.stub();

Creates an anonymous stub function.

	var stub = sinon.stub(object, "method");

Replaces object.method with a stub function. The original function can be restored by calling object.method.restore(); (or stub.restore();). An exception is thrown if the property is not already a function, to help avoid typos when stubbing methods.

var stub = sinon.stub(object, "method", func);

Replaces object.method with a func, wrapped in a spy. As usual, object.method.restore(); can be used to restore the original method.

	var stub = sinon.stub(obj);

Stubs all the object’s methods. Note that it’s usually better practice to stub individual methods, particularly on objects that you don’t understand or control all the methods for (e.g. library dependencies). Stubbing individual methods tests intent more precisely and is less susceptible to unexpected behavior as the object’s code evolves. If you want to create a stub object of MyConstructor, but don’t want the constructor to be invoked, use this utility function.

    var stub = sinon.createStubInstance(MyConstructor)
Stub method Description
stub.withArgs(arg1[, arg2, ...]); Stubs the method only for the provided arguments. This is useful to be more expressive in your assertions, where you can access the spy with the same call. It is also useful to create a stub that can act differently in response to different arguments.
stub.onCall(n); Defines the behavior of the stub on the nth call. Useful for testing sequential interactions.
stub.onFirstCall(); Alias for stub.onCall(0);
stub.onSecondCall(); Alias for stub.onCall(1);
stub.onThirdCall(); Alias for stub.onCall(2);
stub.returns(obj); Makes the stub return the provided value.
stub.returnsArg(index); Causes the stub to return the argument at the provided index. stub.returnsArg(0); causes the stub to return the first argument.
stub.returnsThis(); Causes the stub to return its this value. Useful for stubbing jQuery-style fluent APIs.
stub.throws(); Causes the stub to throw an exception (Error).
stub.throws("TypeError"); Causes the stub to throw an exception of the provided type.
stub.throws(obj); Causes the stub to throw the provided exception object.
stub.callsArg(index); Causes the stub to call the argument at the provided index as a callback function. stub.callsArg(0); causes the stub to call the first argument as a callback.
stub.callsArgOn(index, context); Like above but with an additional parameter to pass the this context.
stub.callsArgWith(index, arg1, arg2, ...); Like callsArg, but with arguments to pass to the callback.
stub.callsArgOnWith(index, context, arg1, arg2, ...); Like above but with an additional parameter to pass the this context.
stub.yields([arg1, arg2, ...]) Almost like callsArg. Causes the stub to call the first callback it receives with the provided arguments (if any). If a method accepts more than one callback, you need to use callsArg to have the stub invoke other callbacks than the first one.
stub.yieldsOn(context, [arg1, arg2, ...]) Like above but with an additional parameter to pass the this context.
stub.yieldsTo(property, [arg1, arg2, ...]) Causes the spy to invoke a callback passed as a property of an object to the spy. Like yields, yieldsTo grabs the first matching argument, finds the callback and calls it with the (optional) arguments.
stub.yieldsToOn(property, context, [arg1, arg2, ...]) Like above but with an additional parameter to pass the this context.
spy.yield([arg1, arg2, ...]) Invoke callbacks passed to the spy with the given arguments. If the spy was never called with a function argument, yield throws an error. Also aliased as invokeCallback.
spy.yieldTo(callback, [arg1, arg2, ...]) Invokes callbacks passed as a property of an object to the spy. Like yield, yieldTo grabs the first matching argument, finds the callback and calls it with the (optional) arguments.
spy.callArg(argNum) Like yield, but with an explicit argument number specifying which callback to call. Useful if a function is called with more than one callback, and simply calling the first callback is not desired.
spy.callArgWith(argNum, [arg1, arg2, ...]) Like `callArg`, but with arguments.
stub.callsArgAsync(index); Same as their corresponding non-Async counterparts, but with callback being deferred (executed not immediately but after short timeout and in another “thread”)
stub.callsArgOnAsync(index, context);
stub.callsArgWithAsync(index, arg1, arg2, ...);
stub.callsArgOnWithAsync(index, context, arg1, arg2, ...);
stub.yieldsAsync([arg1, arg2, ...])
stub.yieldsOnAsync(context, [arg1, arg2, ...])
stub.yieldsToAsync(property, [arg1, arg2, ...])
stub.yieldsToOnAsync(property, context, [arg1, arg2, ...]) Same as their corresponding non-Async counterparts, but with callback being deferred (executed not immediately but after short timeout and in another “thread”)

Mock

link: docs

	var mock = sinon.mock(obj);

Creates a mock for the provided object. Does not change the object, but returns a mock object to set expectations on the object’s methods.

	var expectation = mock.expects("method");

Overrides obj.method with a mock function and returns it. See expectations below.

	mock.restore();

Restores all mocked methods.

	mock.verify();

Verifies all expectations on the mock. If any expectation is not satisfied, an exception is thrown. Also restores the mocked methods.

Expectation method Description
var expectation = sinon.expectation.create([methodName]); Creates an expectation without a mock object, basically an anonymous mock function. Method name is optional and is used in exception messages to make them more readable.
var expectation = sinon.mock(); The same as the above.
expectation.atLeast(number); Specify the minimum amount of calls expected.
expectation.atMost(number); Specify the maximum amount of calls expected.
expectation.never(); Expect the method to never be called.
expectation.once(); Expect the method to be called exactly once.
expectation.twice(); Expect the method to be called exactly twice.
expectation.thrice(); Expect the method to be called exactly thrice.
expectation.exactly(number); Expect the method to be called exactly number times.
expectation.withArgs(arg1, arg2, ...); Expect the method to be called with the provided arguments and possibly others.
expectation.withExactArgs(arg1, arg2, ...); Expect the method to be called with the provided arguments and no others.
expectation.on(obj); Expect the method to be called with obj as this.
expectation.verify(); Verifies the expectation and throws an exception if it’s not met.

### Matchers
Matchers method Description
sinon.match(number) Requires the value to be == to the given number.
sinon.match(string) Requires the value to be a string and have the expectation as a substring.
sinon.match(regexp) Requires the value to be a string and match the given regular expression.
sinon.match(object) Requires the value to be not null or undefined and have at least the same properties as expectation. This supports nested matchers.
sinon.match(function) See [custom matchers](#sinonCustomMatchers)
sinon.match.any Matches anything.
sinon.match.defined Requires the value to be defined.
sinon.match.truthy Requires the value to be truthy.
sinon.match.falsy Requires the value to be falsy.
sinon.match.bool Requires the value to be a boolean.
sinon.match.number Requires the value to be a number.
sinon.match.string Requires the value to be a string.
sinon.match.object Requires the value to be an object.
sinon.match.func Requires the value to be a function.
sinon.match.array Requires the value to be an array.
sinon.match.regexp Requires the value to be a regular expression.
sinon.match.date Requires the value to be a date object.
sinon.match.same(ref) Requires the value to strictly equal ref.
sinon.match.typeOf(type) Requires the value to be of the given type, where type can be one of "undefined", "null", "boolean", "number", "string", "object", "function", "array", "regexp" or "date".
sinon.match.instanceOf(type) Requires the value to be an instance of the given type.
sinon.match.has(property[, expectation]) Requires the value to define the given property. The property might be inherited via the prototype chain. If the optional expectation is given, the value of the property is deeply compared with the expectation. The expectation can be another matcher.
sinon.match.hasOwn(property[, expectation]) Same as sinon.match.has but the property must be defined by the value itself. Inherited properties are ignored.

All matchers implement and and or. This allows to logically combine mutliple matchers. The result is a new matchers that requires both (and) or one of the matchers (or) to return true.

	var stringOrNumber = sinon.match.string.or(sinon.match.number);

	var bookWithPages = sinon.match.instanceOf(Book).and(sinon.match.has("pages"));
#### Custom matchers

Custom matchers are created with the sinon.match factory which takes a test function and an optional message. The test function takes a value as the only argument, returns true if the value matches the expectation and false otherwise. The message string is used to generate the error message in case the value does not match the expectation.

var trueIsh = sinon.match(function (value) {
    return !!value;
}, "trueIsh");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment