Skip to content
A high-level API for `fakeServer` in Sinon.js
JavaScript
Find file
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.
test
.gitignore
LICENSE
README.md
bower.json
package.json
responseFaker.js

README.md

responseFaker.js

High-level abstractions over Sinon.js fakeServer to make your tests less noisy.

There are two helpers:

  • fakeResponse which returns the same response for all AJAX requests.
  • fakeResponses which returns different responses based on specified URLs.

fakeResponse

Instead of writing:

var response = '[{"id":12,"comment":"Hey there"}]';
var server = sinon.fakeServer.create();
server.respondWith([200, { "Content-Type": "application/json" }, response]);

// perform ajax request

server.respond();
server.restore();

… you can write:

var response = { id: 12, comment: "Hey there"; };
fakeResponse(response, function() {
  // perform ajax request
  // the response defaults to JSON with status code 200
});

You can also specify status code and headers yourself:

var response = { id: 12, comment: "Hey there"; };
var options = {
  statusCode: 200,
  headers: { "Content-Type": "application/json" }
}
fakeResponse(response, options, function() {
  // perform ajax request
});

fakeResponses

var responses = {
  // as object which can be JSON stringified
  "/emails": [{ from: "mail@kimjoar.net", subject: "Testing" }],

  // as JSON string
  "/user": '{ "username": "kimjoar" }',

  // object which contain response, statuscode, and/or headers
  "/fail": {
    response: { error: "Not found" },
    statusCode: 404
  }
}

fakeResponses(responses, function() {
  // perform ajax requests to `/emails`, `/user` and `/fail`
});

Include the helpers

You can include fakeResponse and fakeResponses in any object, including the global object:

var obj = {};
responseFaker.call(obj)
// you now have `obj.fakeResponse` and `obj.fakeResponses`

// or, to the global object, i.e. `window` in browsers
responseFaker.call(window);
// you can now call `fakeResponse` and `fakeResponses` directly all over
// your code
Something went wrong with that request. Please try again.