Skip to content

Instantly share code, notes, and snippets.

@Jeffy2012
Last active August 29, 2015 14:03
Show Gist options
  • Save Jeffy2012/164589010f7a77382be1 to your computer and use it in GitHub Desktop.
Save Jeffy2012/164589010f7a77382be1 to your computer and use it in GitHub Desktop.
Sinon.js XMLHttpRequest Demo
describe('XMLHttpRequest Demo', function () {
var xhr, requests;
beforeEach(function () {
xhr = sinon.useFakeXMLHttpRequest();
requests = [];
xhr.onCreate = function (XHR) {
requests.push(XHR);
};
});
afterEach(function () {
xhr.restore();
});
it("$.ajax test", function () {
var spy = sinon.spy();
var model = $.extend($({}), {
fetch: function () {
var self = this;
$.ajax({
url: '/test',
data: {
name: 'Jeffy'
}
}).done(function (data) {
self.trigger('load', [data, self]);
});
}
});
model.bind('load', spy);
model.bind('load', function (e, data, model) {
model.name = data.name;
model.age = data.age;
});
model.fetch();
expect(spy).to.not.be.called;
requests[0].respond(200, { "Content-Type": "application/json" }, testJSON);
expect(spy).to.be.called;
model.fetch();
expect(spy).to.be.have.callCount(1);
requests[1].respond(200, { "Content-Type": "application/json" }, '{ "name" : "tudou ", "age" : 9 }');
expect(spy).to.be.have.callCount(2);
expect(spy.args[1][1]).to.eql({ "name" : "tudou ", "age" : 9 });
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment