Skip to content

Instantly share code, notes, and snippets.

@so-c
Last active December 17, 2015 00:49
Show Gist options
  • Save so-c/5523666 to your computer and use it in GitHub Desktop.
Save so-c/5523666 to your computer and use it in GitHub Desktop.
Sinon.JSのGetting started (http://sinonjs.org/) サンプルコードを、JsTestDriverに合わせて書き換えた。
// Example of ajax
TestCase('AjaxExample', {
'test makes a GET request for todo items':sinon.test(function(stub) {
this.stub($, 'ajax');
getTodos(42, sinon.spy());
assertTrue($.ajax.calledWithMatch({url: '/todo/42/items'}));
})
});
// Example of Fake Server
TestCase('FakeServerExample', sinon.testCase({
'test calls callback with deserialized data': function(server) {
this.server = sinon.fakeServer.create();
var callback = sinon.spy();
getTodos(42, callback);
// This is part of the FakeXMLHttpRequest API
this.server.requests[0].respond(
200,
{'Content-Type': 'application/json'},
JSON.stringify([{id: 1, text: 'Provide example', done: true}])
);
assert(callback.calledOnce);
}
}));
// Example of fake XMLHttpRequest
TestCase('FakeXMLHttpRequestExample', sinon.testCase({
setUp: function() {
this.xhr = sinon.useFakeXMLHttpRequest();
var requests = this.requests = [];
this.xhr.onCreate = function(req) {
requests.push(req);
};
},
'test makes a GET request for todo items': function() {
getTodos(42, sinon.spy());
assertEquals(this.requests.length, 1);
assertEquals(this.requests[0].url, '/todo/42/items');
}
}));
// Example of spy
sinon.assert.expose(this);
TestCase('SpyExample', {
'test calls the original function':function() {
var callback = sinon.spy();
var proxy = once(callback);
proxy();
assertCalled(callback);
},
'test calls the original function only once':function() {
var callback = sinon.spy();
var proxy = once(callback);
proxy();
proxy();
assertCalledOnce(callback);
},
'test calls original function with right this and args':function() {
var callback = sinon.spy();
var proxy = once(callback);
var obj = {};
proxy.call(obj, 1, 2, 3);
assertCalledOn(callback, obj);
assertCalledWith(callback, 1, 2, 3);
}
});
// Example of stub
TestCase('StubExample', {
'test returns the return value from the original function':function() {
var callback = sinon.stub().returns(42);
var proxy = once(callback);
assertEquals(42, proxy());
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment