// Anonymous function
var spy = sinon.spy();
// Anonymous named function
var spy = sinon.spy().named('a callback');
// Provided Function
var spy = sinon.spy(myFunc);
// Existing object and function
var spy = sinon.spy(object, "method");
// Pass the spy as a function
PubSub.subscribe("message", spy);
// Spy on existing function
sinon.spy(jQuery, "ajax");
// Use function
jQuery.getJSON("/some/resource");
// Assert
expect(jQuery.ajax).to.have.been.called;
// Restore afterwards
jQuery.ajax.restore();
Test stubs are functions (spies) with pre-programmed behavior.
// Anonymous stub
var stub = sinon.stub();
// Replace object.method with a stub function
var stub = sinon.stub(object, "method", func);
// Restore original method
stub.restore();
// Stub a whole object
var stub = sinon.stub(obj);
Instead of
sinon.assertCalledWith(mySpy, "foo");
call
expect(mySpy).to.have.been.calledWith("foo");
Sinon Syntax | Sinon-Chai Assertion |
---|---|
called |
expect(spy).to.have.been.called |
calledOnce |
expect(spy).to.have.been.calledOnce |
calledTwice |
expect(spy).to.have.been.calledTwice |
calledThrice |
expect(spy).to.have.been.calledThrice |
calledBefore |
expect(spy1).to.have.been.calledBefore(spy2) |
calledAfter |
expect(spy1).have.been.calledAfter(spy2) |
calledWithNew |
expect(spy).to.have.been.calledWithNew |
alwaysCalledWithNew |
expect(spy).to.always.have.been.calledWithNew |
calledOn |
expect(spy).to.have.been.calledOn(context) |
alwaysCalledOn |
expect(spy).to.always.have.been.calledOn(context) |
calledWith |
expect(spy).to.have.been.calledWith(...args) |
alwaysCalledWith |
expect(spy).to.always.have.been.calledWith(...args) |
calledWithExactly |
expect(spy).to.have.been.calledWithExactly(...args) |
alwaysCalledWithExactly |
expect(spy).to.always.have.been.calledWithExactly(...args) |
calledWithMatch |
expect(spy).to.have.been.calledWithMatch(...args) |
alwaysCalledWithMatch |
expect(spy).to.always.have.been.calledWithMatch(...args) |
returned |
expect(spy).to.have.returned(returnVal) |
alwaysReturned |
expect(spy).to.have.always.returned(returnVal) |
threw |
expect(spy).to.have.thrown(errorObjOrErrorTypeStringOrNothing) |
alwaysThrew |
expect(spy).to.have.always.thrown(errorObjOrErrorTypeStringOrNothing) |