Skip to content

Instantly share code, notes, and snippets.

@RobinClowers
Created March 6, 2012 05:19
Show Gist options
  • Save RobinClowers/1983757 to your computer and use it in GitHub Desktop.
Save RobinClowers/1983757 to your computer and use it in GitHub Desktop.
Sinon js extensions
// regular jasmine api
this.server.respondWith("GET", "/some/article/comments.json", [
200, {
"Content-Type": "application/json"
}, '[{ "id": 12, "comment": "Hey there" }]'
]);
// extension api
this.server.on("GET", "/some/article/comments.json").respond(200, {
id: 121,
comment: "Hey there"
sinon.fakeServer.on = function(method, url) {
return new sinon.fakeServer.requestSpecification(this, method, url);
};
// Implementation
var getResponse;
sinon.fakeServer.requestsForUrl = function(url) {
var results;
results = [];
$.each(this.requests, function(index, request) {
if (request.url === url) {
return results.push(request);
}
});
return results;
};
getResponse = function(response) {
if (response == null) {
return "";
}
return JSON.stringify(response);
};
sinon.fakeServer.requestSpecification = function(server, method, url) {
this.server = server;
this.method = method;
this.url = url;
return this.respond = function(statusCode, response) {
this.server.respondWith(this.method, this.url, [
statusCode, {
"Content-Type": "application/json"
}, getResponse(response)
]);
return this;
};
};
// jasmine matcher
beforeEach(function() {
return this.addMatchers({
toHaveReceivedRequestFor: function(url) {
return this.actual.requestsForUrl(url).length > 0;
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment