Stateful API mock server
Yet another API mock server. Why? Because it has to be simple and I didn't find a simple one in my case (independent api) based on directory file. It's mostly useful if your api use another api.
Just put a js/json file into a directory, start your server from your mocha/karma/etc and use the simple API to create your test cases.
Features
- Independent mock server
- Totally stateful to facilitate unit tests
- Easy to use state API base on route paths
How to use
In your tests file
var ApiMockServer = ; var api = options<object>; apistart{ // write your tests case here};
or with mocha
var ApiMockServer = ; var api = options<object>; ;
Endpoints to File directory
tests/api-mocks/ L users/ L get.json # 200 GET /users response L get-404.json # 404 GET /users response L :id/ L get.json # 200 GET /users/:id response L post.json # 200 POST /users/:id response L cars/ L get.json # 200 GET /cars response L get-404.json # 404 GET /cars response
Use default case
It's possible to define common response in a _defaults
directory to avoid file duplication, like 404.
tests/api-mocks/ L _defaults L get-404.json # 404 GET default response L users/ L get.json # 200 GET /users response L :id/ L get.json # 200 GET /users/:id response L post.json # 200 POST /users/:id response L cars/ L get.json # 200 GET /cars response
Change response state
Imagine this test case suite:
Now you want to test the 404 case
/!\ Important!
If you set a state to unknown construct file (like GET 403 and ./get-403 and /_defaults/get-403 does not exist) it will return 503 and log an error in your terminal
Finally you can reset all
API
Constructor API
Default values:
var api = port: 7000 // Port to launch mocked api mockDir: 'tests/api-mocks' // Relative path to your mocks;
State API
.set(Path<String>, Verb<String>, State<Number|String>)
Set Set a route to demanded state and set status response if State is a number.
// Return get-404.[ext] file and setapistate; // Return get-another.[ext] file and set status to 200apistate;
.get(Path<String>, Verb<String>)
Get Get a route state
apistate;
.getAll()
Get All Get all route states
apistate;
.reset(Path<String>, Verb<String>)
Reset Reset a state to 200
apistate;
.resetAll()
Reset All Reset all routes to 200
apistate;
Debug
To debug you can filter on this domain: stateful-api-mock-server
For example
DEBUG=stateful-api-mock-server:* npm test
TODO
- Remove ext option