Chaos Request
Chaos Request changes the behavior of fetch
. You can change body of the response,
status code or throw exception.
This project was inspired by Chaos Monkey
Installation
npm install [--save-dev] chaos-request # or yarn add [--dev] chaos-request
Usage
; const shouldChangeResponse = { return true;}; const getResponse = { return body: JSON init: status: 200 statusText: 'OK' headers: 'Content-type': 'application/json' ;}; const chaosRequest = shouldChangeResponse getResponse;chaosRequest;
React example
Open index.js
file and import ChaosRequest
module. It takes two parameters, both are functions.
The first function decides if the request should be changed or not. If not, default fetch API will be used. The second function returns an object with two fields: body
and init
. Here you can define what should the fetch return.
Change every response
// index.js;;;; const shouldChangeResponse = { return true;}; const getResponse = { return body: JSON init: status: 200 statusText: 'OK' headers: 'Content-type': 'application/json' ;}; const chaosRequest = shouldChangeResponse getResponse;chaosRequest; ReactDOM;
// App.js; { ; } { return <div></div> }
Change response based on URL
Most probably, you will need to change just some specific request(s). In the next example,
only three requests are overriden and everything else would work without any modification.
Request for https://swapi.co/api/people/1/
returns hard coded object. Request for
https://swapi.co/api/people/2/
will fetch the data from API and change the name field.
The last request for https://swapi.co/api/people/3/
will fail.
// index.js;;;; const shouldChangeResponse = { const url = args0; return false;}; const getResponse = { const url = args0; }; const chaosRequest = shouldChangeResponse getResponse;chaosRequest; ReactDOM;
// App.js; { ; ; ; // Timeout } { return <div></div> }