Install
npm install kodokojo-mocks --save-dev
or
npm install -g kodokojo-mocks
Then create a folder to store your mock files
e.g: {your_project_path}/mocks
Create a config file
e.g: {your_project_path}/mocks_config.json
Config file example :
port
(default: 8080) : Bind server to the specified port (eg: 8080)
logs
(default: true) : Enable request and error logging
prefix
(default: "") : Prefix path (eg: http://localhost:8080 /api/v1/...)
path
(default: "") : Relative path to mocks folder (from your project root folder, where your package.json was created)
routes
(default: []) : An array containing the routes you want to mock. ExpressJs format for parameters and paths
memoryStorage
(default: false) : Use memory only storage
persistStorage
(default: false) : Previous storage file is used if memoryStorage
is false else create a new empty storage file
Usage
Inside your module
Start
var MockServer = ; var mockServer = __dirname+"/mocks_config.json";mockServerstart;
Stop
// ... Server should be startedmockServer;
CLI
Npm script
To run as a npm script. Add the CLI in your package.json
replace {config_file_path}
by your config file path.
{ ...
"scripts": {
"mockserver": "./node_modules/kodokojo-mocks/bin/mockserver.js {config_file_path}"
}
... }
Global installation
npm install -g kodokojo-mocks
Usage
replace {config_file_path}
by your config file path.
mockserver {config_file_path}
Have a look at ./test/index.js to see some examples.
Create your mocks
There is 3 ways to serve a mock : as you can see in the config file above, every mock have a type ("mockType" property) so you can define how the mock will be loaded.
Raw data
Return the value that you specified in your config file ("serve" property)
{... "mockType":"raw","serve":"[value_to_serve]"}
Json file content
Return the content of the given json file
{... "mockType":"file","serve":"[file_name]"}
The mock file should be a standard json file.
You can write data from the incoming request content inside your json file by using mustach syntax, eg :
{ ...
"identifier": "{{req.id}}",
... }
{{req.NAME_OF_PROPERTY_FROM_REQ_OBJECT}}
ExpressJs controller
You can use a classic ExpressJs controller to serve your data, it's allow you to write some custom/business logic as a mock, eg :
{... "mockType":"func","serve":"[file_name]"}
Controller example:
exports { // Your code here ... // Classic ExpressJs api below rescontentType = "application/json"; res; ;};
Persistence
A file based (in-memory if memoryStorage
is true) key-value store is exposed as server.store
that can be
used to store and retrieve data in a custom controller.
exports { store; rescontentType = "application/json"; res; ;};
To do
Enhanced logs
Rename type 'file' to 'json'
rename type 'func' to 'controller'
Npm script