Skip to content

Instantly share code, notes, and snippets.

@techniq
Created June 14, 2015 02:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save techniq/b5c5203ff713ea15f317 to your computer and use it in GitHub Desktop.
Save techniq/b5c5203ff713ea15f317 to your computer and use it in GitHub Desktop.
Sinon AJAX tests
import JSData from 'js-data';
import DSHttpAdapter from 'js-data-http';
import sinon from 'sinon';
describe("fakeServer", function() {
beforeEach(function() {
this.server = sinon.fakeServer.create();
// this.server.autoRespond = true;
// this.respondImmediately = true;
this.store = new JSData.DS();
this.store.registerAdapter('http', new DSHttpAdapter(), { default: true } );
this.User = this.store.defineResource('user');
});
afterEach(function() {
this.server.restore();
});
it("User resource", function(done) {
this.server.respondWith("GET", "user/1",
[200, { "Content-Type": "application/json" }, JSON.stringify({id: 1, name: 'Sean'})]
);
this.User.find(1).then(function(data) {
expect(data).to.exist;
expect(data.id).to.equal(1);
done();
});
setTimeout(_ => this.server.respond(), 10);
});
});
import JSData from 'js-data';
import DSHttpAdapter from 'js-data-http';
import sinon from 'sinon';
describe("FakeXMLHttpRequest", function() {
beforeEach(function() {
this.store = new JSData.DS();
this.store.registerAdapter('http', new DSHttpAdapter(), { default: true } );
this.User = this.store.defineResource('user');
this.xhr = sinon.useFakeXMLHttpRequest();
var requests = this.requests = [];
this.xhr.onCreate = function (xhr) {
requests.push(xhr);
};
});
afterEach(function() {
this.xhr.restore();
});
it("User resource", function(done) {
this.User.find(1).then(function(data) {
expect(data).to.exist;
expect(data.id).to.equal(1);
done();
});
setTimeout(() => {
this.requests[0].respond(200, { "Content-Type": "application/json" }, JSON.stringify({id: 1, name: 'Sean'}));
}, 0);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment