dylanlott
3/21/2017 - 10:27 PM

Sinon Chai assertions in expect style.Examples from http://chaijs.com/plugins/sinon-chai #sinon #chai #javascript

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 SyntaxSinon-Chai Assertion
calledexpect(spy).to.have.been.called
calledOnceexpect(spy).to.have.been.calledOnce
calledTwiceexpect(spy).to.have.been.calledTwice
calledThriceexpect(spy).to.have.been.calledThrice
calledBeforeexpect(spy1).to.have.been.calledBefore(spy2)
calledAfterexpect(spy1).have.been.calledAfter(spy2)
calledWithNewexpect(spy).to.have.been.calledWithNew
alwaysCalledWithNewexpect(spy).to.always.have.been.calledWithNew
calledOnexpect(spy).to.have.been.calledOn(context)
alwaysCalledOnexpect(spy).to.always.have.been.calledOn(context)
calledWithexpect(spy).to.have.been.calledWith(...args)
alwaysCalledWithexpect(spy).to.always.have.been.calledWith(...args)
calledWithExactlyexpect(spy).to.have.been.calledWithExactly(...args)
alwaysCalledWithExactlyexpect(spy).to.always.have.been.calledWithExactly(...args)
calledWithMatchexpect(spy).to.have.been.calledWithMatch(...args)
alwaysCalledWithMatchexpect(spy).to.always.have.been.calledWithMatch(...args)
returnedexpect(spy).to.have.returned(returnVal)
alwaysReturnedexpect(spy).to.have.always.returned(returnVal)
threwexpect(spy).to.have.thrown(errorObjOrErrorTypeStringOrNothing)
alwaysThrewexpect(spy).to.have.always.thrown(errorObjOrErrorTypeStringOrNothing)