Ways to simulate error responses on request in browser?

Viewed 3257

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?

1 Answers

Well, I guess nobody appears to have any suggestions worthy of being an answer so I will give a try fully realizing that this will NOT fully answer your question.

When I have the need for an API that can return various obscure HTTP codes for testing purposes, I use this site: https://httpstat.us/. It's as easy as appending the desired code and making the call (https://httpstat.us/400, https://httpstat.us/404, https://httpstat.us/200 etc.)

Obviously, it cannot do everything you require "Status codes, headers, response body, etc.", but it will sure give the ability to test various HTTP response codes.

Related