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 jasmine-sinon.js in your Jasmine test runner file, or add it to jasmine.yml if you are using jasmine-gem. Don't forget to include sinon.js.
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() |
| returned() | toHaveReturned() |
| alwaysReturned() | toHaveAlwaysReturned() |
| threw() | toHaveThrown() |
| alwaysThrew() | toHaveAlwaysThrown() |
These matchers will work on spies, individual spy calls, stubs and mocks.
jasmine-sinon currently overwrites any Jasmine matchers of the same name used for its own spying features. I plan to allow these to be optionally retained in the future.
The native Jasmine matchers that are overwritten are:
- toHaveBeenCalled()
- toHaveBeenCalledWith()
Thanks to Augusto Rocha Elesbão for adding Exception matchers.