Skip to content

Instantly share code, notes, and snippets.

@dylanlott
Forked from patocallaghan/sinon-chai-expect.md
Created March 21, 2017 22:27
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 dylanlott/5c3f9af13408a9a8e69f7032b87c5498 to your computer and use it in GitHub Desktop.
Save dylanlott/5c3f9af13408a9a8e69f7032b87c5498 to your computer and use it in GitHub Desktop.
Sinon Chai assertions in expect style.Examples from http://chaijs.com/plugins/sinon-chai #sinon #chai #javascript

Sinon JS

##Spies

//Anonymous function
var spy = sinon.spy();

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

//Replaces 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