Skip to content

Instantly share code, notes, and snippets.

@chrisn
Forked from patocallaghan/sinon-chai-expect.md
Last active August 26, 2016 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisn/96252d73de939369e85390016ecd342c to your computer and use it in GitHub Desktop.
Save chrisn/96252d73de939369e85390016ecd342c to your computer and use it in GitHub Desktop.
Sinon Chai assertions in expect style. Examples from http://chaijs.com/plugins/sinon-chai

Sinon JS

Spies

// 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);

Example: Spying on existing methods

// 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();

Stubs

Test stubs are functions (spies) with pre-programmed behavior.

Create Stubs

// 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment