Skip to content

Instantly share code, notes, and snippets.

@ledil
Created June 16, 2016 13:59
Show Gist options
  • Save ledil/ca8d841da93d4692822d291f76e9465d to your computer and use it in GitHub Desktop.
Save ledil/ca8d841da93d4692822d291f76e9465d to your computer and use it in GitHub Desktop.
sinon.js fake server example
/*
Load Sinon.JS in the SpecRunner:
<script type="text/javascript" src="lib/jasmine-1.0.1/jasmine.js"></script>
<script type="text/javascript" src="lib/jasmine-1.0.1/jasmine-html.js"></script>
<script type="text/javascript" src="sinon-1.0.0.js"></script>
<script type="text/javascript" src="sinon-ie-1.0.0.js"></script>
http://cjohansen.no/sinon/
*/
describe("SinonFakeServerWithJasmine", function() {
var server;
beforeEach(function() {
server = sinon.fakeServer.create();
});
afterEach(function () {
server.restore();
});
it("should fake a jQuery ajax request", function () {
server.respondWith("GET", "/something",
[200, { "Content-Type": "application/json" },
'{ "stuff": "is", "awesome": "in here" }']);
var callbacks = [sinon.spy(), sinon.spy()];
jQuery.ajax({
url: "/something",
success: callbacks[0]
});
jQuery.ajax({
url: "/other",
success: callbacks[1]
});
console.log(server.requests); // Logs all requests so far
server.respond(); // Process all requests so far
expect(callbacks[0].calledOnce).toBeTruthy();
expect(callbacks[0].calledWith({
stuff: "is",
awesome: "in here"
})).toBeTruthy();
expect(callbacks[1].calledOnce).toBeFalsy(); // Unknown URL /other received 404
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment