miragejs

MirageJS Error response not causing an error


Following the docs I've set up this handler inside routes():

this.put(
  '/admin/features/error/environment/test',
  // @ts-ignore
  () => new Response(500, {}, { errors: ['The database went on vacation'] }),
);

Mirage does receive what I've set, sort of. Here is its response, from the browser console logs. Note that it's not an error although the 500 shows up in _bodyInit:

{
    "type": "default",
    "status": 200,
    "ok": true,
    "statusText": "",
    "headers": {
        "map": {
            "content-type": "text/plain;charset=UTF-8"
        }
    },
    "url": "",
    "bodyUsed": false,
    "_bodyInit": 500,
    "_bodyText": "[object Number]"
}

Note that I need ts-ignore which is probably a clue. TS complains that new Response expects 0-2 arguments but got 3.


Solution

  • Try importing the Mirage Response class:

    import { Response } from 'miragejs';
    

    Otherwise, Response refers to a Fetch API Response object. This explains the type checking error and the unexpected behavior when calling the route.

    After adding the import you can remove @ts-ignore and requests to the route should fail with status code 500.