sinon.js
Basically, it's awesome
Features
Spies
Stubs
Mocks
Timers
Server
Assertions
Spies
Usage:
var spy = sinon.spy()
or
var spy = sinon.spy(someOtherFunction)
Returns a function that does that same as provided one, as well as adding spy behaviour
Spy API
Call API
Basil integration
this.spy(foo, 'bar');
foo.bar();
foo.bar.firstCall
foo.bar.should.have.been.calledOnce;
Spy will be automatically removed at the end of the test setup
Basil integration
describe("jquery spy", function () {
this.spy(window, '$');
var el = $(document.body);
el.length.should.equal(1);
$.should.have.been
.calledWith(document.body);
});
Stubs
Usage
var stub = sinon.stub();
Returns a function that initially does nothing, but allows you to specify behaviour.
Also implements spy API
Stub API
Example
var stub = sinon.stub();
stub.withArgs('foo').returns('bar');
stub('foo').should.equal('bar');
expect(stub('bar')).to.be.undefined;
stub.should.have.been.calledTwice;
stub.should.have.been.calledWith('foo');
Basil integration
this.stub(document, 'getElementById');
document.getElementById
.withArgs('some-id')
.returns(this.dom);
document.getElementById('some-id')
.should.equal(this.dom);
expect(document.getElementById('foo'))
.to.be.undefined;
Basil integration
this.stub(window, 'setTimeout')
var spy = sinon.spy();
window.setTimeout
.withArgs(sinon.match.any, 0)
.yields();
window.setTimeout(spy, 0);
spy.should.have.been.called;
Mocks
A stub, with built in expectations
Honestly never used them, but the behaviour is similar
Clock
var clock = sinon.useFakeTimers();
var spy = sinon.spy();
setTimeout(spy, 5000);
spy.should.not.have.been.called;
clock.tick(5000);
spy.should.have.been.called;
clock.restore();
Basil integration
var spy = sinon.spy();
setTimeout(spy, 5000);
spy.should.not.have.been.called;
this.clock.tick(5000);
spy.should.have.been.called;
Server
var server = sinon.useFakeServer();
server.respondWith('GET', '/Foo/Bar', [200, {"Content-Type":"text/html"}, 'Contents']);
var response;
$.get('/Foo/Bar', function(result) {
response = result;
});
server.respond();
response.should.equal('Contents')
server.restore();
Assertions
some examples:
spy.should.have.been.called
spy.should.have.been.calledWith('1', '2')
spy.should.have.been.calledOn(thisObj)
spy.should.have.been.calledBefore(spy2)
spy.should.have.thrown(ErrorType)
sinonjs
By xwipeoutx
sinonjs
- 1,145