Use sinonJs FakeServer to mock you API
Sometimes the frontend and the backend starts with there work at the same time. Maybe you have defined the API but it will take some times until you can get data from the backend. As a frontend dev you can use sinonJs' FakeServer to return JSON on a specific route.
First you have to load sinon-server.js. Then start a new fake server. Its important to set the server.xhr.useFiltersuseFilters
to true, otherwise every request would be end in fake server
<script src="sinon-server-1.6.0.js"></script>
<script>
var server = sinon.fakeServer.create();
server.xhr.useFilters = true;
server.autoRespond = true;
</script>
<script src="fake.js"></script>
For every undefined route create a file like this:
server.xhr.addFilter(function(method, url) {
// If the filter returns truthy, the request will not be faked
return !url.match(/routeToMatch/);
});
server.respondWith(/ruleset/,
function(xhr, id) {
xhr.respond(
200,
{"Content-Type": "application/json"},
//return the JSON string
JSON.stringify({some:"jsonData"})
);
});
Written by Andreas Köberle
Related protips
1 Response
Thanks! Was a useful example.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Sinon
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#