jasmine-sinon provides a set of custom matchers for using the Sinon.JS spying, stubbing and mocking library with Jasmine BDD.
Instead of:
expect(mySinonSpy.calledWith('foo')).toBeTruthy();
you can say:
expect(mySinonSpy).toHaveBeenCalledWith('foo');
This is not only nicerer to look at in your purdy specs, but you get more descriptive failure output in your Jasmine spec runner.
Instead of:
Expected false to be truthy.
you get:
Expected Function to have been called.
Just include lib/jasmine-sinon.js
in your Jasmine test runner file.
Don't forget to include sinon.js.
With jasmine-gem
Add it to jasmine.yml
. Don't forget to include sinon.js.
npm install jasmine-sinon --save-dev
Then, in your jasmine spec:
var sinon = require('sinon');
require('jasmine-sinon');
bower install jasmine-sinon --save-dev
Then, include components/jasmine-sinon/index.js
in your test runner.
In general, you should be able to translate a Sinon spy/stub/mock API method to a jasmine-sinon matcher by prepending toHaveBeen to the front of the method name. For example, the Sinon.JS spy method called
becomes toHaveBeenCalled
. There are one or two exceptions to this rule, so the full list of matchers is given below.
Sinon.JS property / method | jasmine-sinon matcher |
---|---|
called | toHaveBeenCalled |
calledOnce | toHaveBeenCalledOnce |
calledTwice | toHaveBeenCalledTwice |
calledThrice | toHaveBeenCalledThrice |
calledBefore() | toHaveBeenCalledBefore() |
calledAfter() | toHaveBeenCalledAfter() |
calledOn() | toHaveBeenCalledOn() |
alwaysCalledOn() | toHaveBeenAlwaysCalledOn() |
calledWith() | toHaveBeenCalledWith() |
alwaysCalledWith() | toHaveBeenAlwaysCalledWith() |
calledWithExactly() | toHaveBeenCalledWithExactly() |
alwaysCalledWithExactly() | toHaveBeenAlwaysCalledWithExactly() |
calledWithMatch() | toHaveBeenCalledWithMatch() |
alwaysCalledWithMatch() | toHaveBeenAlwaysCalledWithMatch() |
returned() | toHaveReturned() |
alwaysReturned() | toHaveAlwaysReturned() |
threw() | toHaveThrown() |
alwaysThrew() | toHaveAlwaysThrown() |
These matchers will work on spies, individual spy calls, stubs and mocks.
You can also use Jasmine spies alongside your Sinon spies. jasmine-sinon will detect which you're using and use the appropriate matcher.
Thanks to:
- @aelesbao for Exception matchers
- @theinterned for, er, match matchers
- @milichev for graceful spy matchers