Last active
July 13, 2018 05:56
-
-
Save mindscratch/5951148 to your computer and use it in GitHub Desktop.
Fake server-side using [Sinon.JS](http://sinonjs.org/). Inspiration from this [presentation](http://emdin.info/r/sinon-talk/).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var srv = sinon.fakeServer.create(); | |
srv.autoRespond = true; // server should automatically respond after a timeout | |
srv.autoRespondAfter = 500; // response timeout in milliseconds | |
srv.xhr.useFitlers = true; // tell Sinon that some requests should not be faked | |
// add a filter that will tell Sinon to allowa all requests to access the server | |
// except fitlers defined when calling Server#fake. | |
srv.xhr.addFilter(function(method, url, async, username, password) { | |
var fakedRequest = _.find(Server.fakedRequests, function(request) { | |
return request.method === method && request.regex.test(url); | |
}); | |
return _.isUndefined(fakedRequest) ? true : false; | |
}); | |
Server = { | |
// keep trak of the faked requests | |
fakedRequests = [], | |
// fake a 'methodToFake' request to a URL that matches 'urlRegex' | |
fake: function(urlRegex, methodToFake, callback) { | |
this.fakedRequests.push({regex: urlRegex, method: methodToFake}); | |
// handle the faked request | |
return srv.respondWith(urlRegex, function(xhr, url) { | |
if (xhr.method != methodToFake) { | |
return; | |
} | |
console.log("[Fake] " + methodToFake + " " + xhr.url); | |
callback.call(undefined, xhr, url); | |
}); | |
} | |
}; | |
// example | |
Server.fake(/widgets$/, 'GET', function(xhr, url) { | |
xhr.respond(200, {'Content-Type': 'application/json'}, [{name: 'Uber Widget', price: 10}, {name: 'Midlevel Widget', price: 4}]); | |
}); | |
// make request | |
$.getJSON('/widgets'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
useFitlers
should beuseFilters
, I assume?