0% found this document useful (0 votes)
17K views17 pages

Ultimate Unit Testing Cheat Sheet

The document provides a cheat sheet for Mocha, Chai and Sinon testing frameworks. It includes a list of Sinon assertions and their Chai equivalents. Then it details the various assertions and chains available in Chai for expectations and property matching including expect, deep, keys, and include flags.

Uploaded by

Davor Vuković
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17K views17 pages

Ultimate Unit Testing Cheat Sheet

The document provides a cheat sheet for Mocha, Chai and Sinon testing frameworks. It includes a list of Sinon assertions and their Chai equivalents. Then it details the various assertions and chains available in Chai for expectations and property matching including expect, deep, keys, and include flags.

Uploaded by

Davor Vuković
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

The Ultimate Unit Testing Cheat-sheet

For Mocha, Chai and Sinon

using mocha/chai/sinon for node.js unit-tests? check out my utility: mocha-stirrer to easily
reuse test components and mock require dependencies

Sinon Chai
Chai
Sinon
Mocha

Sinon Chai
links: GitHub - Chai plugin

Sinon.JS property/method SinonChai assertion


called spy.should.have.been.called
callCount spy.should.have.callCount(n)
calledOnce spy.should.have.been.calledOnce
calledTwice spy.should.have.been.calledTwice
calledThrice spy.should.have.been.calledThrice
calledBefore spy1.should.have.been.calledBefore(spy2)
calledAfter spy1.should.have.been.calledAfter(spy2)
calledWithNew spy.should.have.been.calledWithNew
alwaysCalledWithNew spy.should.always.have.been.calledWithNew
calledOn spy.should.have.been.calledOn(context)
alwaysCalledOn spy.should.always.have.been.calledOn(context)
calledWith spy.should.have.been.calledWith(...args)
alwaysCalledWith spy.should.always.have.been.calledWith(...args)
calledWithExactly spy.should.have.been.calledWithExactly(...args)
alwaysCalledWithExactly spy.should.always.have.been.calledWithExactly(...args)
calledWithMatch spy.should.have.been.calledWithMatch(...args)
alwaysCalledWithMatch spy.should.always.have.been.calledWithMatch(...args)
returned spy.should.have.returned(returnVal)
alwaysReturned spy.should.have.always.returned(returnVal)
threw spy.should.have.thrown(errorObjOrErrorTypeStringOrNothing)
alwaysThrew spy.should.have.always.thrown(errorObjOrErrorTypeStringOrNothing)
Chai
links: chai home , docs

Expect/Should (BDD)

links: docs

Chains:

to
be
been
is
that
which
and
has
have
with
at
of
same

Assertions Description
@param{ String }type
@param{ String }message_optional_
The a and an assertions are aliases that can be used either as language chains or to assert a value's
type.

// typeof
.a(type)
expect('test').to.be.a('string');
expect({ foo: 'bar' }).to.be.an('object');
expect(null).to.be.a('null');
expect(undefined).to.be.an('undefined');
// language chain
expect(foo).to.be.an.instanceof(Foo);
@param{ Number }value
@param{ String }message_optional_
Asserts that the target is greater than value.
expect(10).to.be.above(5);
.above(value)
Can also be used in conjunction with length to assert a minimum length. The benefit being a more
informative error message than if the length was supplied directly.
expect('foo').to.have.length.above(2);
expect([ 1, 2, 3 ]).to.have.length.above(2);
Sets the all flag (opposite of the any flag) later used by the keys assertion.
.all
expect(foo).to.have.all.keys('bar', 'baz');
Sets the any flag, (opposite of the all flag) later used in the keys assertion.
.any
expect(foo).to.have.all.keys('bar', 'baz');
Asserts that the target is an arguments object.

.arguments function test () {


expect(arguments).to.be.arguments;
}
Assertions Description
@param{ Number }value
@param{ String }message_optional_
Asserts that the target is less than value.
expect(5).to.be.below(10);
.below(value)
Can also be used in conjunction with length to assert a maximum length. The benefit being a more
informative error message than if the length was supplied directly.
expect('foo').to.have.length.below(4);
expect([ 1, 2, 3 ]).to.have.length.below(4);
@param{ String }object
@param{ String }propertyname
@param{ String }message_optional_
Asserts that a function changes an object property
.change(function)
var obj = { val: 10 };
var fn = function() { obj.val += 3 };
var noChangeFn = function() { return 'foo' + 'bar'; };
expect(fn).to.change(obj, 'val');
expect(noChangFn).to.not.change(obj, 'val')
@param{ Number }expected
.closeTo(expected, @param{ Number }delta @param{ String }message_optional_
delta) Asserts that the target is equal expected, to within a +/- delta range.
expect(1.5).to.be.closeTo(1, 0.5);
@param{ String }object
@param{ String }propertyname
@param{ String }message_optional_
Asserts that a function decreases an object property
.decrease(function)
var obj = { val: 10 };

var fn = function() { obj.val = 5 };


expect(fn).to.decrease(obj, 'val');
Sets the deep flag, later used by the equal and property assertions.
.deep
expect(foo).to.deep.equal({ bar: 'baz' });
expect({ foo: { bar: { baz: 'quux' } } }).to.have.deep.property('foo.bar.baz', 'quux');
Asserts that the target's length is 0. For arrays, it checks the length property. For objects, it gets the
count of enumerable keys.
.empty
expect([]).to.be.empty;
expect('').to.be.empty;
expect({}).to.be.empty;
@param{ Mixed }value
@param{ String }message_optional_
.eql(value) Asserts that the target is deeply equal to value.
expect([ 1, 2, 3 ]).to.eql([ 1, 2, 3 ]);
expect({ foo: 'bar' }).to.eql({ foo: 'bar' });
@param{ Mixed }value
@param{ String }message_optional_
Asserts that the target is strictly equal (===) to value. Alternately, if the deep flag is set, asserts that
the target is deeply equal to value.
.equal(value) expect('hello').to.equal('hello');
expect(42).to.equal(42);
expect(1).to.not.equal(true);
expect({ foo: 'bar' }).to.not.equal({ foo: 'bar' });
expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' });
Asserts that the target is neither null nor undefined. var foo = 'hi' , bar = null , baz;

.exist
expect(foo).to.exist;
expect(bar).to.not.exist;
expect(baz).to.not.exist;
Asserts that the target is false.
.false expect(false).to.be.false;
expect(0).to.not.be.false;
Assertions Description
@param{ Object | String | Number }obj
@param{ String }message_optional_
The include and contain assertions can be used as either property based language chains or as
methods to assert the inclusion of an object in an array or a substring in a string. When used as
.include(value)
language chains, they toggle the contains flag for the keys assertion.
expect([1,2,3]).to.include(2);
expect('foobar').to.contain('foo');
expect({ foo: 'bar', hello: 'universe' }).to.include.keys('foo');
@param{ String }object
@param{ String }propertyname
@param{ String }message_optional_
.increase(function) Asserts that a function increases an object property
var obj = { val: 10 };
var fn = function() { obj.val = 15 };
expect(fn).to.increase(obj, 'val');
@param{ Constructor }constructor
@param{ String }message_optional_
Asserts that the target is an instance of constructor.
.instanceof(constructor) var Tea = function (name) { this.name = name; }
, Chai = new Tea('chai');
expect(Chai).to.be.an.instanceof(Tea);
expect([ 1, 2, 3 ]).to.be.instanceof(Array);
Sets the itself flag, later used by the respondTo assertion.
function Foo() {}
Foo.bar = function() {}
.itself Foo.prototype.baz = function() {}

expect(Foo).itself.to.respondTo('bar');
expect(Foo).itself.not.to.respondTo('baz');
@param{ String... | Array | Object }keys
Asserts that the target contains any or all of the passed-in keys. Use in combination with any, all,
contains, or have will affect what will pass.
When used in conjunction with any, at least one key that is passed in must exist in the target object.
This is regardless whether or not the have or contain qualifiers are used. Note, either any or all
should be used in the assertion. If neither are used, the assertion is defaulted to all.
When both all and contain are used, the target object must have at least all of the passed-in keys but
may have more keys not listed.
When both all and have are used, the target object must both contain all of the passed-in keys AND
the number of keys in the target object must match the number of keys passed in (in other words, a
.keys(key1, [key2], [...]) target object must have all and only all of the passed-in keys).

expect({ foo: 1, bar: 2 }).to.have.any.keys('foo', 'baz');


expect({ foo: 1, bar: 2 }).to.have.any.keys('foo');
expect({ foo: 1, bar: 2 }).to.contain.any.keys('bar', 'baz');
expect({ foo: 1, bar: 2 }).to.contain.any.keys(['foo']);
expect({ foo: 1, bar: 2 }).to.contain.any.keys({'foo': 6});
expect({ foo: 1, bar: 2 }).to.have.all.keys(['bar', 'foo']);
expect({ foo: 1, bar: 2 }).to.have.all.keys({'bar': 6, 'foo', 7});
expect({ foo: 1, bar: 2, baz: 3 }).to.contain.all.keys(['bar', 'foo']);
expect({ foo: 1, bar: 2, baz: 3 }).to.contain.all.keys([{'bar': 6}}]);
@param{ Number }value
@param{ String }message_optional_
.least(value)
Asserts that the target is greater than or equal to value.
expect(10).to.be.at.least(10);
@param{ Number }length
@param{ String }message_optional_

Asserts that the target's length property has the expected value.
expect([ 1, 2, 3]).to.have.length(3);
expect('foobar').to.have.length(6);
Can also be used as a chain precursor to a value comparison for the length property.
.length(value)
expect('foo').to.have.length.above(2);
expect([ 1, 2, 3 ]).to.have.length.above(2);
expect('foo').to.have.length.below(4);
expect('foo').to.have.length.below(4);
expect([ 1, 2, 3 ]).to.have.length.below(4);
expect('foo').to.have.length.within(2,4);
expect([ 1, 2, 3 ]).to.have.length.within(2,4);
Assertions Description
@param{ RegExp }RegularExpression
@param{ String }message_optional_
.match(regexp)
Asserts that the target matches a regular expression.
expect('foobar').to.match(/^foo/);
@param{ Array }set
@param{ String }message_optional_
Asserts that the target is a superset of set, or that the target and set have the same strictly-equal
(===) members. Alternately, if the deep flag is set, set members are compared for deep equality.
.members(set) expect([1, 2, 3]).to.include.members([3, 2]);
expect([1, 2, 3]).to.not.include.members([3, 2, 8]);
expect([4, 2]).to.have.members([2, 4]);
expect([5, 2]).to.not.have.members([5, 2, 1]);
expect([{ id: 1 }]).to.deep.include.members([{ id: 1 }]);
@param{ Number }value
@param{ String }message_optional_
Asserts that the target is less than or equal to value.
expect(5).to.be.at.most(5);
.most(value)
Can also be used in conjunction with length to assert a maximum length. The benefit being a more
informative error message than if the length was supplied directly.
expect('foo').to.have.length.of.at.most(4);
expect([ 1, 2, 3 ]).to.have.length.of.at.most(3);
Negates any of assertions following in the chain.
expect(foo).to.not.equal('bar');
.not
expect(goodFn).to.not.throw(Error);
expect({ foo: 'baz' }).to.have.property('foo').and.not.equal('bar');
Asserts that the target is null.
.null
expect(null).to.be.null;
expect(undefined).not.to.be.null;
.ok Asserts that the target is truthy.
@param{ String }name
@param{ String }message_optional_
.ownProperty(name)
Asserts that the target has an own property name.
expect('test').to.have.ownProperty('length');
Assertions Description
@param{ String }name
@param{ Mixed }value(optional)
@param{ String }message_optional_
Asserts that the target has a property name, optionally asserting that the value of that property is
strictly equal to value. If the deep flag is set, you can use dot- and bracket-notation for deep
references into objects and arrays.
// simple referencing
var obj = { foo: 'bar' };

expect(obj).to.have.property('foo');
expect(obj).to.have.property('foo', 'bar');

// deep referencing
var deepObj = {
green: { tea: 'matcha' }
, teas: [ 'chai', 'matcha', { tea: 'konacha' } ]
};

expect(deepObj).to.have.deep.property('green.tea', 'matcha');
.property(name,
expect(deepObj).to.have.deep.property('teas[1]', 'matcha');
[value])
expect(deepObj).to.have.deep.property('teas[2].tea', 'konacha');
You can also use an array as the starting point of a deep.property assertion, or traverse nested
arrays.
var arr = [
[ 'chai', 'matcha', 'konacha' ]
, [ { tea: 'chai' }
, { tea: 'matcha' }
, { tea: 'konacha' } ]
];

expect(arr).to.have.deep.property('[0][1]', 'matcha');
expect(arr).to.have.deep.property('[1][2].tea', 'konacha');
Furthermore, property changes the subject of the assertion to be the value of that property from the
original object. This permits for further chainable assertions on that property.
expect(obj).to.have.property('foo').that.is.a('string');
expect(deepObj).to.have.property('green').that.is.an('object').that.deep.equals({ tea: 'matcha' });

expect(deepObj).to.have.property('teas').that.is.an('array').with.deep.property('[2]').that.deep.equals({
tea: 'konacha' });
@param{ String }method
@param{ String }message_optional_
Asserts that the object or class target will respond to a method.
Klass.prototype.bar = function(){};

.respondTo(method) expect(Klass).to.respondTo('bar');
expect(obj).to.respondTo('bar');
To check if a constructor will respond to a static function, set the itself flag.
Klass.baz = function(){};

expect(Klass).itself.to.respondTo('baz');
@param{ Function }matcher
@param{ String }message_optional_
.satisfy(method)
Asserts that the target passes a given truth test.
expect(1).to.satisfy(function(num) { return num > 0; });
@param{ String }string
@param{ String }message_optional_
.string(string)
Asserts that the string target contains another string.
expect('foobar').to.have.string('bar');
Assertions Description
@param{ ErrorConstructor }constructor
@param{ String | RegExp }expectederror message
@param{ String }message_optional_
@see: [https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types]()
Asserts that the function target will throw a specific error, or specific type of error (as determined
using instanceof), optionally with a RegExp or string inclusion test for the error's message.

var err = new ReferenceError('This is a bad function.');


var fn = function () { throw err; }

.throw(constructor) expect(fn).to.throw(ReferenceError);
expect(fn).to.throw(Error);
expect(fn).to.throw(/bad function/);
expect(fn).to.not.throw('good function');
expect(fn).to.throw(ReferenceError, /bad function/);
expect(fn).to.throw(err);
expect(fn).to.not.throw(new RangeError('Out of range.'));
Please note that when a throw expectation is negated, it will check each parameter independently,
starting with error constructor type. The appropriate way to check for the existence of a type of error
but for a message that does not match is to use and.
expect(fn).to.throw(ReferenceError) .and.not.throw(/good function/);
Asserts that the target is true.
.true expect(true).to.be.true;
expect(1).to.not.be.true;
Asserts that the target is undefined.
.undefined expect(undefined).to.be.undefined;
expect(null).to.not.be.undefined;
@param{ Number }startlowerbound inclusive
@param{ Number }finishupperbound inclusive
@param{ String }message_optional_
Asserts that the target is within a range.
expect(7).to.be.within(5,10);
.within(start, finish)
Can also be used in conjunction with length to assert a length range. The benefit being a more
informative error message than if the length was supplied directly.
expect('foo').to.have.length.within(2,4);
expect([ 1, 2, 3 ]).to.have.length.within(2,4);

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
Returns true if the spy was called at least once with obj as
spy.calledOn(obj);
this
spy.alwaysCalledOn(obj); Returns true if the spy was always called with obj as this.
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
spy.calledWith(arg1, arg2, ...);
arguments, so a call that received the provided arguments
(in the same spots) and possibly others as well will return
true.
Returns true if spy was always called with the provided
spy.alwaysCalledWith(arg1, arg2, ...);
arguments (and possibly others).
Returns true if spy was called at least once with the
spy.calledWithExactly(arg1, arg2, ...);
provided arguments and no others.
spy.alwaysCalledWithExactly(arg1, Returns true if spy was always called with the exact
arg2, ...); provided arguments.
Returns true if spy was called with matching arguments
spy.calledWithMatch(arg1, arg2, ...); (and possibly others). This behaves the same as
spy.calledWith(sinon.match(arg1), sinon.match(arg2), ...).
Returns true if spy was always called with matching
spy.alwaysCalledWithMatch(arg1, arg2, arguments (and possibly others). This behaves the same
...); as spy.alwaysCalledWith(sinon.match(arg1),
sinon.match(arg2), ...).
Returns true if spy/stub was called the new operator.
Beware that this is inferred based on the value of the this
spy.calledWithNew();
object and the spy functions prototype, so it may give
false positives if you actively return the right kind of object.
Returns true if the spy/stub was never called with the
spy.neverCalledWith(arg1, arg2, ...);
provided arguments.
Spy method Description
Returns true if the spy/stub was never called with
spy.neverCalledWithMatch(arg1, arg2, 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.
Returns true if spy threw an exception of the provided
spy.threw("TypeError");
type at least once.
Returns true if spy threw the provided exception object at
spy.threw(obj);
least once.
spy.alwaysThrew(); Returns true if spy always threw an exception.
Returns true if spy always threw an exception of the
spy.alwaysThrew("TypeError");
provided type.
Returns true if spy always threw the provided exception
spy.alwaysThrew(obj);
object.
Returns true if spy returned the provided value at least
once. Uses deep comparison for objects and arrays. Use
spy.returned(obj);
spy.returned(sinon.match.same(obj)) for strict comparison
(see Matchers).
spy.alwaysReturned(obj); Returns true if spy always returned the provided value.
Returns the nth call). Accessing individual calls helps with
more detailed behavior verification when the spy is called
more than once. Example:
var spyCall = spy.getCall(n);
sinon.spy(jQuery, "ajax");
jQuery.ajax("/stuffs");
var spyCall = jQuery.ajax.getCall(0);
assertEquals("/stuffs", spyCall.args[0]);
Array of this objects, spy.thisValues[0] is the this object for
spy.thisValues
the first call.
Array of arguments received, spy.args[0] is an array of
spy.args
arguments received in the first call.
Array of exception objects thrown, spy.exceptions[0] is the
exception thrown by the first call. If the call did not throw
spy.exceptions
an error, the value at the calls location in .exceptions will
be undefined.
Array of return values, spy.returnValues[0] is the return
value of the first call. If the call did not explicitly return a
spy.returnValues
value, the value at the calls location in .returnValues will
be undefined.
spy.reset() Resets the state of a spy.
Spy method Description
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.)
spy.printf(format string", [arg1, arg2, %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
Returns the nth [call](#spycall). Accessing individual calls
var spyCall = spy.getCall(n) 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.
Returns true if call received provided arguments (and
spyCall.calledWith(arg1, arg2, ...);
possibly others).
Returns true if call received provided arguments and no
spyCall.calledWithExactly(arg1, arg2, ...);
others.
Returns true if call received matching arguments (and
possibly others). This behaves the same as
spyCall.calledWithMatch(arg1, arg2, ...);
spyCall.calledWith(sinon.match(arg1), sinon.match(arg2),
...).
spyCall.notCalledWith(arg1, arg2, ...); Returns true if call did not receive provided arguments.
Returns true if call did not receive matching arguments.
spyCall.notCalledWithMatch(arg1, arg2, 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 calls this value.
spyCall.args Array of received arguments.
spyCall.exception Exception thrown, if any.
spyCall.returnValue Return value.

Stublink: 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 objects methods. Note that its usually better practice to stub individual methods,
particularly on objects that you dont 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 objects code evolves. If you want to create a stub object of
MyConstructor, but dont want the constructor to be invoked, use this utility function. var stub
= sinon.createStubInstance(MyConstructor)

Stub method Description


Stubs the method only for the provided arguments.
This is useful to be more expressive in your
stub.withArgs(arg1[, arg2, ...]); 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.
Defines the behavior of the stub on the nth call.
stub.onCall(n);
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.
Causes the stub to return the argument at the
stub.returnsArg(index); provided index. stub.returnsArg(0); causes the stub
to return the first argument.
Causes the stub to return its this value. Useful for
stub.returnsThis();
stubbing jQuery-style fluent APIs.
stub.throws(); Causes the stub to throw an exception (Error).
Causes the stub to throw an exception of the
stub.throws("TypeError");
provided type.
Causes the stub to throw the provided exception
stub.throws(obj);
object.
Causes the stub to call the argument at the
provided index as a callback function.
stub.callsArg(index);
stub.callsArg(0); causes the stub to call the first
argument as a callback.
Like above but with an additional parameter to pass
stub.callsArgOn(index, context);
the this context.
Like callsArg, but with arguments to pass to the
stub.callsArgWith(index, arg1, arg2, ...);
callback.
stub.callsArgOnWith(index, context, arg1, Like above but with an additional parameter to pass
arg2, ...); the this context.
Almost like callsArg. Causes the stub to call the first
callback it receives with the provided arguments (if
stub.yields([arg1, arg2, ...]) 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.
Like above but with an additional parameter to pass
stub.yieldsOn(context, [arg1, arg2, ...])
the this context.
Causes the spy to invoke a callback passed as a
property of an object to the spy. Like yields, yieldsTo
stub.yieldsTo(property, [arg1, arg2, ...])
grabs the first matching argument, finds the
callback and calls it with the (optional) arguments.
Stub method Description
stub.yieldsToOn(property, context, [arg1, Like above but with an additional parameter to pass
arg2, ...]) the this context.
Invoke callbacks passed to the spy with the given
arguments. If the spy was never called with a
spy.yield([arg1, arg2, ...])
function argument, yield throws an error. Also
aliased as invokeCallback.
Invokes callbacks passed as a property of an object
to the spy. Like yield, yieldTo grabs the first
spy.yieldTo(callback, [arg1, arg2, ...])
matching argument, finds the callback and calls it
with the (optional) arguments.
Like yield, but with an explicit argument number
specifying which callback to call. Useful if a function
spy.callArg(argNum)
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.
Same as their corresponding non-Async
counterparts, but with callback being deferred
stub.callsArgAsync(index);
(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, ...])
Same as their corresponding non-Async
stub.yieldsToOnAsync(property, context, counterparts, but with callback being deferred
[arg1, arg2, ...]) (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 objects 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
Creates an expectation without a mock
object, basically an anonymous mock
var expectation =
function. Method name is optional and is
sinon.expectation.create([methodName]);
used in exception messages to make
them more readable.
var expectation = sinon.mock(); The same as the above.
Specify the minimum amount of calls
expectation.atLeast(number);
expected.
Expectation method Description
Specify the maximum amount of calls
expectation.atMost(number);
expected.
expectation.never(); Expect the method to never be called.
Expect the method to be called exactly
expectation.once();
once.
Expect the method to be called exactly
expectation.twice();
twice.
Expect the method to be called exactly
expectation.thrice();
thrice.
Expect the method to be called exactly
expectation.exactly(number);
number times.
Expect the method to be called with the
expectation.withArgs(arg1, arg2, ...);
provided arguments and possibly others.
Expect the method to be called with the
expectation.withExactArgs(arg1, arg2, ...);
provided arguments and no others.
Expect the method to be called with obj
expectation.on(obj);
as this.
Verifies the expectation and throws an
expectation.verify();
exception if its not met.

Matchers
Matchers method Description
sinon.match(number) Requires the value to be == to the given number.
Requires the value to be a string and have the
sinon.match(string)
expectation as a substring.
Requires the value to be a string and match the given
sinon.match(regexp)
regular expression.
Requires the value to be not null or undefined and have
sinon.match(object) 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.
Matchers method Description
Requires the value to be of the given type, where type can
sinon.match.typeOf(type) 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.
Requires the value to define the given property. The
property might be inherited via the prototype chain. If the
sinon.match.has(property[,
optional expectation is given, the value of the property is
expectation])
deeply compared with the expectation. The expectation
can be another matcher.
Same as sinon.match.has but the property must be
sinon.match.hasOwn(property[,
defined by the value itself. Inherited properties are
expectation])
ignored.
Combining matchers 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");

Mocha links: home


Method Description
describe('Array', function(){
describe('#indexOf()', function(){
it('should return -1 when the value is not present', function(){
[1,2,3].indexOf(5).should.equal(-1);
Synchronous code
[1,2,3].indexOf(0).should.equal(-1);
})
})
})
describe('User', function(){
describe('#save()', function(){
it('should save without error', function(done){
var user = new User('Luna');
user.save(function(err){
Asynchronous code if (err) throw err;
done();
});
})
})
})
describe('User', function(){ describe('#save()', function(){ it('should save
Done with Error without error', function(done){ var user = new User('Luna'); user.save(done); })
}) })
Method Description
describe('hooks', function() {

before(function() {
// runs before all tests in this block
})

after(function(){
// runs after all tests in this block
})

beforeEach(function(){
hooks
// runs before each test in this block
})

afterEach(function(){
// runs after each test in this block
})

// test cases
})

Each hook also accepting done as first parameter to support async methods
describe('Array', function(){
describe('#indexOf()', function(){
Pending tests it('should return -1 when the value is not present');
})
})
describe('Array', function(){
describe.only('#indexOf()', function(){
...
})
})

Or a specific test-case: describe('Array', function(){


describe('#indexOf()', function(){
Exclusive tests
it.only('should return -1 unless present', function(){
})

it('should return the index when present', function(){


})
})
})
Method Description
describe('Array', function(){
describe.skip('#indexOf()', function(){
...
})
})

Or a specific test-case: describe('Array', function(){


describe('#indexOf()', function(){
Inclusive tests
it.skip('should return -1 unless present', function(){
})

it('should return the index when present', function(){


})
})
})
Flags Usage: mocha [debug] [options] [files]
Flag Description
-w, --watch Executes tests on changes to JavaScript in the CWD, and once initially.
coffee-script is no longer supported out of the box. CS and similar transpilers may
be used by mapping the file extensions (for use with --watch) and the module name.
--compilers
For example --compilers coffee:coffee-script with CoffeeScript 1.6- or --compilers
coffee:coffee-script/register with CoffeeScript 1.7+.
-b, --bail Only interested in the first exception? use --bail !
Enables node's debugger support, this executes your script(s) with node debug
allowing you to step through code and break with the debugger statement. Note the
-d, --debug difference between mocha debug and mocha --debug: mocha debug will fire up
node's built-in debug client, mocha --debug will allow you to use a different interface
such as the Blink Developer Tools.
Accepts a comma-delimited list of accepted global variable names. For example,
suppose your app deliberately exposes a global named app and YUI, you may want
--globals to add --globals app,YUI. It also accepts wildcards. You could do --globals '*bar' and
it would match foobar, barbar, etc. You can also simply pass in '*' to ignore all
globals.
By default Mocha will not check for global variables leaked while running tests, to
--check-leaks enable this pass --check-leaks, to specify globals that are acceptable use --globals,
for example --globals jQuery,MyLib.
The --require option is useful for libraries such as should.js, so you may simply
--require should instead of manually invoking require('should') within each test file.
Note that this works well for should as it augments Object.prototype, however if you
-r, --require
wish to access a module's exports you will have to require them, for example var
should = require('should'). Furthermore, it can be used with relative paths, e.g.
--require ./test/helper.js
-u, --ui The --ui option lets you specify the interface to use, defaulting to "bdd".
The --reporter option allows you to specify the reporter that will be used, defaulting
to "dot". This flag may also be used to utilize third-party reporters. For example if
-R, --reporter
you npm install mocha-lcov-reporter you may then do --reporter
mocha-lcov-reporter.
Specifies the test-case timeout, defaulting to 2 seconds. To override you may pass
-t, --timeout the timeout in milliseconds, or a value with the s suffix, ex: --timeout 2s or --timeout
2000 would be equivalent.
Flag Description
Specify the "slow" test threshold, defaulting to 75ms. Mocha uses this to highlight
-s, --slow
test-cases that are taking too long.
The --grep option when specified will trigger mocha to only run tests matching the
-g, --grep
given pattern which is internally compiled to a RegExp.

You might also like