Skip to content

Instantly share code, notes, and snippets.

@Jeffy2012
Last active August 4, 2021 08:56
Show Gist options
  • Save Jeffy2012/426f0c261e813808f0af to your computer and use it in GitHub Desktop.
Save Jeffy2012/426f0c261e813808f0af to your computer and use it in GitHub Desktop.
Sinon.js Spy Demo
function test() {
return arguments[0];
}
var obj = {
test: test,
call: function (fn, args, context) {
context = context || null;
if (Array.isArray(args)) {
fn.apply(context, args);
} else {
fn();
}
}
};
describe("Spy Demo", function () {
it('var spy = sinon.spy(fn);', function () {
var spy = sinon.spy(test);
spy(123);
expect(spy.called).to.equal(true);
expect(spy.callCount).to.equal(1);
expect(spy.calledWith(123)).to.equal(true);
expect(spy.returned(123)).to.equal(true);
spy.reset();
spy({name: 'Jeffy'}, 27);
expect(spy.args[0][0]).to.eql({name: 'Jeffy'});
expect(spy.args[0][0]).to.have.property('name', 'Jeffy');
sinon.assert.calledWith(spy, sinon.match({name: 'Jeffy'}));
expect(spy.callCount).to.equal(1);
spy.reset();
});
it('var spy = sinon.spy();', function () {
var spy = sinon.spy();
obj.call(spy);
expect(spy.called).to.equal(true);
expect(spy.returnValues[0]).to.be.an('undefined');
spy.reset();
obj.call(spy, [1, 2, 3]);
expect(spy.calledWith(1, 2, 3)).to.equal(true);
expect(spy.args[0]).to.eql([1, 2, 3]);
obj.call(spy, ['Jeffy'], {name: 'Jeffy'});
expect(spy.firstCall.args).to.eql([1, 2, 3]);
expect(spy.thisValues[1]).to.eql({name: 'Jeffy'});
expect(spy.callCount).to.eq(2);
});
it('var spy = sinon.spy(object, "method");', function () {
var spy = sinon.spy(obj, 'test');
obj.test();
expect(spy.called).to.equal(true);
expect(obj.test.called).to.equal(true);
obj.test(1,2,3);
obj.test([1,2,3],{name:'Jeffy'});
expect(obj.test.callCount).to.equal(3);
expect(obj.test.thisValues[0]).to.equal(obj);
expect(obj.test.firstCall.args).to.be.empty;
expect(obj.test.secondCall.args).to.eql([1,2,3]);
expect(obj.test.thirdCall.calledWith([1,2,3],{name:'Jeffy'})).to.equal(true);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment