Mocking network requests can be useful for a variety of use-cases, such as testing your frontend without running a backend, overwriting feature flag configurations, or testing error states.

Mocking a route

In this examples, we’ll capture requests to our /todos endpoint, and return fake data instead of hitting our production API server. First, we’ll create a new mock route step, and set the URL matcher to a regex that will capture requests to /todos.
Then, we define a response generator to create fake data.
const url = new URL(mock.request.url)

const fakeTodo = {
    id: url.searchParams.get("id"),
    name: "My todo item",
    done: false,
    description: "An item that I need to do",
}

return new Response(
    JSON.stringify([fakeTodo]),
    {
        status: 200,
        headers: {
            "content-type": "application/json"
        }
    }
)

Modifying the response from the original server

Sometimes, it’s easier to simply modify the original response from the server, for example, in order to set a specific feature flag. In order complete the initial request, and pass the response to the mock generator, you must first enable the “fetch real response” configuration. This will allow us to access the response at mock.response inside our Javascript code.
Now we can configure our mock to intercept feature flag requests.
And define a response to overwrite one of the values.
return new Response(
  JSON.stringify({
    ...mock.response.json,
    flags: {
        ...mock.response.json.flags,
        momentic_test: true,
    }
  }),
  {
    status: mock.response.status,
    headers: mock.response.headers
  }
)