Tom Mathew Tom Mathew - 1 month ago 5x
JSON Question

What is the difference between returning a Mirage.Response object vs returning a raw JSON object through Mirage?

I am trying to build an EmberJS test server in the browser. I have an API call to "myApiMethod", from which I am trying to GET a JSON object. While trying to test the response from a specific method I found out that that I can either return a raw json object, or wrap it in a Mirage.Response object. Since I wanted the mock server's response to be reflective of the real world, I wasn't sure which of the two was a better idea.

What I wanted to know was the functional differences between the following two chunks of code that I have in my Mirage's config.js:

Version 1:

this.get('/myApiMethod', function(param1, param2){
var jsonObject = myFunctionThatReturnsJson(param1, param2);
return jsonObject;


Version 2:

this.get('/myApiMethod',function(param1, param2){
var jsonObject = myFunctionThatReturnsJson(param1, param2);
return Mirage.Response(200, {}, jsonObject);


Mirage uses Pretender.js under the hood to fake XHR responses. Pretender itself is unopinionated about the response type, so when responding with JSON you need to manually stringify it. Here's an example from the docs:

this.get('/photos/:id', function(request) {
  return [200, {"Content-Type": "application/json"}, JSON.stringify(PHOTOS[])]

One of the original decisions in Mirage was to assume that, most of the time, folks want to respond with JSON. So, route handlers in Mirage let you return plain JavaScript objects:

this.get('/photos/:id', () => {
  return [{ id: 1, url: '' }];

and Mirage takes care of stringifying the response and setting the appropriate ContentType header.

The Mirage.Response object was added for people who want to customize their response, either to respond with a different content type, change the headers, or use a different HTTP response code than the default for the given verb.

In short, if you need something other than the default behavior, use Mirage.Response.