# The Ultimate Unit Testing Cheat-sheet ### _For_ Mocha, Chai and Sinon ___ * [Sinon Chai](#sinon-chai) * [Chai](#chai) * [Sinon](#sinon) * [Mocha](#mocha) ## Sinon Chai links: [GitHub](https://github.com/domenic/sinon-chai) - [Chai plugin](http://chaijs.com/plugins/sinon-chai)
| Sinon.JS property/method | Sinon–Chai 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) |
| Assertions | Description |
|---|---|
| .a(type) |
@param{ String }type // typeof
|
| .above(value) |
@param{ Number }value Asserts that the target is greater than 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.
|
| .all | Sets the all flag (opposite of the any flag) later used by the keys assertion.
|
| .any | Sets the any flag, (opposite of the all flag) later used in the keys assertion.
|
| .arguments | Asserts that the target is an arguments object.
function test () { expect(arguments).to.be.arguments; } |
| .below(value) |
@param{ Number }value Asserts that the target is less than 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.
|
| .change(function) |
@param{ String }object
Asserts that a function changes an object property
|
| .closeTo(expected, delta) |
@param{ Number }expected Asserts that the target is equal expected, to within a +/- delta range.
|
| .decrease(function) |
@param{ String }object Asserts that a function decreases an object property var obj = { val: 10 };var fn = function() { obj.val = 5 };
|
| .deep | Sets the deep flag, later used by the equal and property assertions.
|
| .empty | Asserts that the target's length is 0. For arrays, it checks the length property. For objects, it gets the count of enumerable keys.
|
| .eql(value) |
@param{ Mixed }value Asserts that the target is deeply equal to value.
|
| .equal(value) |
@param{ Mixed }value 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.
|
| .exist | Asserts that the target is neither null nor undefined.
var foo = 'hi'
, bar = null
, baz;
|
| .false | Asserts that the target is false.
|
| .include(value) |
@param{ Object | String | Number }obj 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 language chains, they toggle the contains flag for the keys assertion.
|
| .increase(function) |
@param{ String }object Asserts that a function increases an object property var obj = { val: 10 };var fn = function() { obj.val = 15 };
|
| .instanceof(constructor) |
@param{ Constructor }constructor Asserts that the target is an instance of constructor. var Tea = function (name) { this.name = name; }, Chai = new Tea('chai');
|
| .itself | Sets the itself flag, later used by the respondTo assertion.
function Foo() {} Foo.bar = function() {} Foo.prototype.baz = function() {}
|
| .keys(key1, [key2], [...]) |
@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.
|
| .least(value) |
@param{ Number }value Asserts that the target is greater than or equal to value.
|
| .length(value) |
@param{ Number }length
Can also be used as a chain precursor to a value comparison for the length property.
|
| .match(regexp) |
@param{ RegExp }RegularExpression Asserts that the target matches a regular expression.
|
| .members(set) |
@param{ Array }set 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.
|
| .most(value) |
@param{ Number }value Asserts that the target is less than or equal to 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.
|
| .not | Negates any of assertions following in the chain.
|
| .null | Asserts that the target is null.
|
| .ok | Asserts that the target is truthy. |
| .ownProperty(name) |
@param{ String }name Asserts that the target has an own property name.
|
| .property(name, [value]) |
@param{ String }name 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 referencingvar obj = { foo: 'bar' };
// deep referencing var deepObj = { green: { tea: 'matcha' } , teas: [ 'chai', 'matcha', { 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' } ] ];
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.
|
| .respondTo(method) |
@param{ String }method Asserts that the object or class target will respond to a method. Klass.prototype.bar = function(){};
To check if a constructor will respond to a static function, set the itself flag. Klass.baz = function(){};
|
| .satisfy(method) |
@param{ Function }matcher Asserts that the target passes a given truth test.
|
| .string(string) |
@param{ String }string Asserts that the string target contains another string.
|
| .throw(constructor) |
@param{ ErrorConstructor }constructor var err = new ReferenceError('This is a bad function.'); var fn = function () { throw err; }
|
| .true | Asserts that the target is true.
|
| .undefined | Asserts that the target is undefined.
|
| .within(start, finish) |
@param{ Number }startlowerbound inclusive
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.
|
| 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:
|
| 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. |
| 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”) |
| 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 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. |
| Method | Description |
|---|---|
| Synchronous code |
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); [1,2,3].indexOf(0).should.equal(-1); }) }) }) |
| Asynchronous code |
describe('User', function(){ describe('#save()', function(){ it('should save without error', function(done){ var user = new User('Luna'); user.save(function(err){ if (err) throw err; done(); }); }) }) }) |
| Done with Error | describe('User', function(){ describe('#save()', function(){ it('should save without error', function(done){ var user = new User('Luna'); user.save(done); }) }) }) |
| hooks |
describe('hooks', function() { before(function() { // runs before all tests in this block }) after(function(){ // runs after all tests in this block }) beforeEach(function(){ // 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 |
| Pending tests | describe('Array', function(){ describe('#indexOf()', function(){ it('should return -1 when the value is not present'); }) }) |
| Exclusive tests | describe('Array', function(){ describe.only('#indexOf()', function(){ ... }) }) Or a specific test-case: describe('Array', function(){ describe('#indexOf()', function(){ it.only('should return -1 unless present', function(){ }) it('should return the index when present', function(){ }) }) }) |
| Inclusive tests | describe('Array', function(){ describe.skip('#indexOf()', function(){ ... }) }) Or a specific test-case: describe('Array', function(){ describe('#indexOf()', function(){ it.skip('should return -1 unless present', function(){ }) it('should return the index when present', function(){ }) }) }) |
| Flag | Description |
|---|---|
| -w, --watch | Executes tests on changes to JavaScript in the CWD, and once initially. |
| --compilers | 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. 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 ! |
| -d, --debug | Enables node's debugger support, this executes your script(s) with node debug |
| --globals |
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 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. |
| --check-leaks | By default Mocha will not check for global variables leaked while running tests, to enable this pass --check-leaks, to specify globals that are acceptable use --globals, for example --globals jQuery,MyLib. |
| -r, --require |
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 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". |
| -R, --reporter |
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 you npm install mocha-lcov-reporter you may then do --reporter mocha-lcov-reporter. |
| -t, --timeout |
Specifies the test-case timeout, defaulting to 2 seconds. To override you may pass the timeout in milliseconds, or a value with the s suffix, ex: --timeout 2s or --timeout 2000 would be equivalent. |
| -s, --slow |
Specify the "slow" test threshold, defaulting to 75ms. Mocha uses this to highlight test-cases that are taking too long. |
| -g, --grep |
The --grep option when specified will trigger mocha to only run tests matching the given pattern which is internally compiled to a RegExp. |