Mockster
A library for mocking fetch responses.
Install
npm i --save mockster
;
Note: window.fetch
is automatically mocked when including this library. It's a good idea to only include mocks in a mock build so this usually isn't an issue. If you need them the library also exports fetchHook
and fetchUnhook
, as well as fetchUnmock(url, method)
.
Tip: You can include mocks in a webpack build with no extra config. Create a mocks/index.js
file at your root and run npm start -- mocks
.
Usage
Supported methods: delete
, get
, patch
, post
, put
.
mockster; ;
You can also return error responses:
mockster; ;
You can also return a Promise if you want to delay the response or do async work:
mockster;
Parameters
Parameters are avaiable in the second arguments (params). URLs support params, splats, and optional segments.
Example | Description |
---|---|
:name |
a parameter to capture from the route up to / , ? , or end of string |
*splat |
a splat to capture from the route up to ? or end of string |
() |
Optional group that doesn't have to be part of the query. Can contain nested optional groups, params, and splats |
anything else | free form literals |
Some examples:
/some/(optional/):thing
/users/:id/comments/:comment/rating/:rating
/*a/foo/*b
/books/*section/:title
/books?author=:author&subject=:subject
Matching based on options
It is also possible to match based on options as well as the URL. A deep equal will be performed on the options you wish to compare:
mockster;
Not all options will pass an equality check (for example FormData), to this effect options can also be a function:
mockster;