miragejs: request object inspection

2020-09-26

 | 

~2 min read

 | 

204 words

When mocking out APIs, you want them to mirror the actual API closely so that you don’t have something work in testing and then fail in production.

So, how do you mock out a request where query parameters or the request body matters?

The second argument of the route handler is the request object.

I have found that normally I don’t need access to the request object, or the schema (the first argument), because my API mocking has not reached that level of sophistication yet. But when I did need it, it was nice to know it existed.

For example, I was making a call to an API endpoint and it was important for the server that certain query parameters be included:

`api/resource?foo=bar

Remembering the components of the URL, the route is api/resource, but I wanted MirageJS to still check for the query parameters just like the backend would. The solution was to inspect the request object.

import { Server, Response } from "miragejs"
new Server({
  routes() {
    this.get("api/resource", (_, request) => {
      if (request.queryParams["foo"] === "bar") return new Response(200)
      return new Response(500, {}, { error: "Missing parameters" })
    })
  },
  environment: process.env.NODE_ENV === "test" ? "test" : "development",
})


Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!