Search code examples
javascriptmockingfetch

Ways to simulate error responses on request in browser?


I'd like to exercise my JavaScript error handling code with actual error responses when making HTTP requests to a server backend. Therefore, I'm looking for a simple way to simulate a response, with a given status codes, headers, response body, etc.

With msw package, I can setup a service worker which catches requests and generates responses:

import { rest } from "msw";

const BASE_PATH = "https://localhost:3000";

export const handlers = [
  rest.get(`${BASE_PATH}/hello`, (req, res, ctx) => {
    return res(ctx.status(200), ctx.json({ data: "Hello!" }));
  }),
  rest.get(`${BASE_PATH}/error`, (req, res, ctx) => {
    return res(ctx.status(400), ctx.json({ message: "Bad request" }));
  })
} 

However, that requires some code to wire up. It would be nicer to have something in Chrome Dev Tools that allow me to modify responses, similar to how I can block requests to some routes.

What is the easiest way of simulating the response of an HTTP request in the browser?


Solution

  • Was looking for the same thing and found this Chrome extension called Tweak which offers exactly this, it allows you to mock requests without needing to write code, you can mock responses including the status code, payload, and headers.