Last Updated: July 25, 2019
· eskimoblood

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>
   var server = sinon.fakeServer.create();
   server.xhr.useFilters = true;
   server.autoRespond = true;

 <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/);


  function(xhr, id) {
      {"Content-Type": "application/json"},
      //return the JSON string 

1 Response
Add your response

Thanks! Was a useful example.

over 1 year ago ·