Giter Club home page Giter Club logo

node-mock-server's Introduction

node-mock-server

File based Node REST API mock server

Build status npm npm Codestyle

node-mock-server-ui.png

Getting Started

This application requires Node 6 or higher. For Node <6 please use [email protected] For Node <4 please use [email protected]

1. Install npm package:
$ npm install node-mock-server --save-dev
2. Start init process:
$ node node_modules/node-mock-server/init

Options

node-mock-server options

Usage examples

node-mock-server usage examples

Features

CLI

$ node <nodeScript> --help

  Usage
    $ node <nodeScript> [--version] [--help] <command> [<args>]

  Options
    $                  start mock server
    $ --version        print node-mock-server version
    $ --help           print help
    $ swagger-import   run a swagger import
    $ validate         run a validation for all mock data
    $ collections      print all available collections
    $ collection <id>  activate collection

  Examples
    $ node demo/index.js --version
    $ node demo/index.js collections

Demo

git clone https://github.com/smollweide/node-mock-server.git
cd node-mock-server
npm install
node demo

License

MIT License

Changelog

Please see the Releases

node-mock-server's People

Contributors

blasphemouse avatar btmpl avatar dependabot[bot] avatar dfrencham avatar dschulten avatar easingthemes avatar hypery2k avatar johannesmarx avatar mrbrownser avatar pmcilwaine avatar rev42 avatar sebastiandeutsch avatar smollweide avatar snyk-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-mock-server's Issues

Express is not a function

I'm getting the following error when trying to run

node app.js
Type error: express is not a function

Am I doing something wrong?

Response headers/cookies example/test?

I have a mock with response login-ok.json and added login-ok.header.json (sic: header not headers) that contains {"Set-Cookie":"sessionid=asdfasdf", "Other": "asdfasdf" }, yet I detect neither with the response.

Do you have a test or sample? Can you see what I'm doing wrong?

request body validation for POST requests ??

Hi,
Can we validate request body for POST requests ,For instance, If I'm sending XML data to POST method, I want to validate the presence of mandatory elements presence in post XML data to the API ?? If mandatory XML elements were missing I should throw exception accordingly, can we such validations ??

Regards.

Preview not working with as expected with params in success.json

If I use a param in success.js without quotes like this:

"componentId": <%params.id%>

The produced preview can not be parsed by the browser because the param will leave an empty space in preview. It works if the params in enclosed with quotes (of course)

Result:
"[\r\n\t{\r\n\t\t\"id\": 3,\r\n\t\t\"componentId\": ,\r\n\t\t\"name\": \"Recept 3\",\r\n\t\t\"image\": \"https://unsplash.it/200/?random\",\r\n\t\t\"cookingTime\": 60\r\n\t},\r\n\t{\r\n\t\t\"id\": 4,\r\n\t\t\"name\": \"Recept 4\",\r\n\t\t\"componentId\": ,\r\n\t\t\"image\": \"https://unsplash.it/200/?random\",\r\n\t\t\"cookingTime\": 30\r\n\t},\r\n\t{\r\n\t\t\"id\": 5,\r\n\t\t\"name\": \"Recept 4\",\r\n\t\t\"componentId\": ,\r\n\t\t\"image\": \"https://unsplash.it/200/?random\",\r\n\t\t\"cookingTime\": 30\r\n\t},\r\n\t{\r\n\t\t\"id\": 6,\r\n\t\t\"name\": \"Recept 4\",\r\n\t\t\"componentId\": ,\r\n\t\t\"image\": \"https://unsplash.it/200/?random\",\r\n\t\t\"cookingTime\": 30\r\n\t},\r\n\t{\r\n\t\t\"id\": 7,\r\n\t\t\"name\": \"Recept 4\",\r\n\t\t\"componentId\": ,\r\n\t\t\"image\": \"https://unsplash.it/200/?random\",\r\n\t\t\"cookingTime\": 30\r\n\t}\r\n]"

OPTIONS request gives me a 500 (obviously)

Hi,

the frontend I'm using is doing an OPTIONS request due to checking the CORS headers. Will I need to add OPTIONS as a mocked http verb for every other verb to avoid a 500 (due to file not found) or do I miss something in the configuration.

Thanks

Move `protocol` to separate option

When using ssl default http://localhost:3001 is opened.

Currently default options are:

	urlBase: 'http://localhost:3001',
	port: 3001,
	open: true,

If you want to use ssl than https module is used:

if (this.options.privateKey && this.options.certificate) {
    this.server = https.createServer({
  1. But urlBase still has http protocol and that is opened as default:
if (options.open) {
    open(options.urlBase + options.uiPath);
}
  1. Also port is configurable option, but again urlBase stays the same, although I've never saw any issues with this.

Maybe urlBase can be split into protocol, domain and port as configurable options:

const options = {
        ...
	domain:   'localhost',
	port:     3001,
	protocol: 'http'
        ...
}

and than create urlBase from options:

const { protocol, domain, port, urlBase = `${protocol}://${domain}:${port}` } = options;

Simple solution is to use urlBase as https://localhost:3001, so I'm not sure if this is worth implementing or it's quite enough to add this info in readme.

What do you think?

desc.json response status code not respected

I am creating a series of POST and PUT endpoints. When the mock server responds to these requests, I want to specify that they return the correct http status code:

If I specify that status code in the response object within desc.json, it is not being respected and always returns 200 (unless I use an error response with an error-401.json kind of response file).

"response": {
"statusCode": 201,
"schema": {
"type": "application/json"
}
}

I am using v0.14.0

Tunnel

  • Tunnel per endpoint
  • Enable / disable tunnels for all endpoints
  • Store 5 latest tunnel responses and allow user to save them as mock response

UI element to add new resource

The UI can only be used to add new responses once the following folder structure exists:

resource-url-segment
  #path
    +--- method
      +--- mock 

It would be very useful to have an Add Resource button in the UI which asks for the resource url, #path and method so that I do not have to create the above structure manually. Similar to:

Resource: ______
Path: #_____________ (separate path segments with #)
Method: ___ (GET, POST ...)
[Create]

Question: Different 2xx status codes?

I wonder if there is some way to use other status codes than 200 OK for non error responses. Like, for example, how would I send a 204. Maybe I missed this funcionality. but I could not find a way. Not even as an "error".

Edit: I found about #64 Maybe for success it could be the same as for error (example: success-204.json)

Thank you!

Request param value missing

I have updated to the 0.7.2, but can't get the request param to work. It turns up empty.

desc.json

{
    "desc": "Returns a list of recipes for a specific component",
    "security": [],
    "protected": false,
    "status": "open",
    "request": {
        "uri": {
            "parameters": [
                {
                    "name": "id",
                    "required": true,
                    "type": "integer",
                    "desc": "Id of campaign"
                }
            ]
        }
    },
    "response": {
        "statusCode": 200,
        "schema": {
            "type": "application/json"
        }
    }
}

response_schema.json

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "Recipes",
  "type": "array",
  "items": {
    "properties": {
        "id": {
            "type": "integer"
        },
        "componentId": {
            "type": "integer"
        },
        "name": {
            "type": "string"
        },
        "image": {
            "type": "string"
        },
        "cookingTime": {
            "type": "integer"
        }
    }
  }
}

success.json

[
    {
        "id": 3,
        "componentId": <%params.id%>,
        "name": "Recept 3",
        "image": "https://unsplash.it/200/?random",
        "cookingTime": 60
    }

[Request] Ability to dynamically change status response code

I'm doing some basic parameter validation on one of my mocks and would like to be able to return a different status code when a parameter is missing or incorrect. Currently, the only way this can be done is to create a separate error response and select it using the UI.

Not able to change status code for error response

How to simulate response with status other than 200.

**Below is the success.json file.**
<%

var data = {};

var init = params.id;

    switch (init) {
        case '1':
        data = response[init];
        console.log("I am "+ init);
        break;
        case '2':
        data = response['error'];
        console.log("I am "+ init);
        break;  
        default:
        data= response['error-401'];
            break;
    }
%>

<%-JSON.stringify(data);%>

In all the case the response is going with 200 as status code. But for error response , am expecting status code as 400.
Please help with some code snippet through which we can change status code based on scenarios.

Can't run the server over SSL/TLS: Self-signed certificate not loaded

Hi @smollweide, while using the mock server within a project that encrypts HTTP traffic (SSL, TLS) we found an issue with the self-signed SSL certificate. After creating one with openssl terminal utility, we are not able to run the server.

Here is my local setup:
node 8.9.2
npm 5.6.0
mock server 0.22.0

And configuration of the server:

var mockServer = require('node-mock-server');
var path = require('path');

mockServer({
    'restPath': path.join(__dirname, '/rest'),
    'uiPath': '/',
    'title': 'JSON Mock Server',
    'version': 1,
    'urlBase': 'https://test.local:3001',
    'urlPath': '/rest/v1',
    'port': 3001,
    'certificate': path.join(__dirname, '/test.crt'),
    'privateKey': path.join(__dirname, '/test.key'),
    'contentType': 'application/json',
    'accessControlExposeHeaders': 'X-Total-Count',
    'accessControlAllowOrigin': '*',
    'accessControlAllowMethods': 'GET, POST, PUT, OPTIONS, DELETE, PATCH, HEAD',
    'accessControlAllowHeaders': 'origin, x-requested-with, content-type',
    'accessControlAllowCredentials': 'true',
    'headers': {},
    'open': true,
    'dirName': __dirname
});

Error trace:

> node run-mock-server.js

_tls_common.js:88
      c.context.setCert(options.cert);
                ^
Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
    at Object.createSecureContext (_tls_common.js:88:17)
    at Server (_tls_wrap.js:803:25)
    at new Server (https.js:54:14)
    at Object.createServer (https.js:76:10)
    at AppController.init(...)
    ...

It looks like some dependency issue, did you experience a similar problem?
Thanks.

Question: How do I create different success.json based on a param?

I have not yet figured this one out and need help.

Folder structure:

test#{id}

test#{id}/GET

test#{id}/GET/mock

Example:
Call: /rest/test/1
Response should be:

{
      "id": 1,
      name: "John"
}

Call: /rest/test/2
Response should be:

{
      "id": 2,
      name: "Sven"
}

Edit. Also i don't figure out how to show error.json if no ID is supplied when doing the GET.

options.dirName and serving static content

I am looking for a possibility to serve static content (html, css, js, images) not via the rest api definitions, but just from an arbitrary folder. Right now I am serving static content through a separate server on localhost on a different port, but that makes things more complicated since I need CORS.

I was hoping serving static content could be done with options.dirName. It is documented like this:

options.dirName
Type: String
A string value that defines the root directory (__dirname).

I tried
options.dirName: __dirname
options.dirName: __dirname + '/public
options.dirName: __dirname + '/../public

and put a file foo.html to __dirname (the folder where index.js resides), __dirname/public and a /public folder right beside __dirname, but I was never able to get the http://localhost:3003/foo.html. Rather I got the usual error response for a missing rest resource definition:

Error: ENOENT: no such file or directory, open 'C:\foo.html#\OPTIONS\mock\response.txt'

Two questions arise:
Is it possible to serve arbitrary static content through node-mock-server?
If options.dirName does not define the folder where static content is served from, what is its purpose?

Set headers into response

Hi,
I'm doing some experiments with your library but I'm facing with not clear instructions.
For example: how can I set the headers in the GET/POST mock response?

I would suggest you to write a more detailed user guide or some example too, because there's a bit messy right now.

Create response functions while swagger DTO import

Example "PriceDTO" schema:

"price": {
  "currency": "string",
  "price": {
    "value": {
      "type": "number"
    }
  }
}

PriceDTO response function

module.exports = {

    price: function (price, currency) {

        price = price || 0;
        currency = currency || '€';

        return JSON.stringify({
            currency: currency,
            price: {
                value: price
            }
        });
    }

};

The response function can be used in expected response like this:

{
    "price": <%-price();%>,
    "highlight": true
}

how to post in middleware

Hello,

How can I send a POST require with a JSON? I was thinking in use a middleware but I dont know if requestOptions is available with the post data inside.

Thanks in advance

Placeholder at uri first level

Hi! Thank you for this awesome tool :)

I'm trying to build a mock server where the first part of the uri path (what would be the "group" directory in the folder structure) is a dynamic path param. Something like:
localhost:3001/{apiVersion}/somethingElse.

I changed the default urlPath to '' and then placed a directory named #apiVersion under rest. But that didn't work. I also tried using a group directory called # and in it the #apiVersion one, and finally tried putting the dynamic path param in the default urlPath, but that didn't work either.

Is it possible to do this? Can you help me out see what I'm missing?

Thank you again!

ReST responses that are not json

I tried to create a success.html containing an html fragment instead of json and use the radiobutton to select it. The response was empty and the log showed that response.txt was set to success.html, but an error stating that success.json could not be found.

Ideally, it should consider the Accept request header, so it would be possible to choose 'success' (not success. html), then request always the same resource and get success.json when Accept:application/json was requested, success.xml for application/xml, success.html for text/html etc.

response function rules with parent node

currently a rule can be defined for one level

responseFuncRules: {
    ruleTest1: 'Rule value'
}

a parent should also be possible

responseFuncRules: {
    'parent.ruleTest1': 'Rule value'
}

Demo - /products does not work for Windows

When running node demo and surfing to localhost:3001/products I get following response:

Error: ENOENT: no such file or directory, open 'c:\products#\GET\mock\response.txt'
at Error (native)
at Object.fs.openSync (fs.js:640:18)
at Object.fs.writeFileSync (fs.js:1333:33)
at MockController.writeFile (c:\projects\nodeMocker\node-mock-server\lib\Utils.js:152:6)
at MockController._handleMockRequest (c:\projects\nodeMocker\node-mock-server\lib\controller\MockController.js:193:9)
at Layer.handle [as handle_request] (c:\projects\nodeMocker\node-mock-server\node_modules\express\lib\router\layer.js:95:5)
at next (c:\projects\nodeMocker\node-mock-server\node_modules\express\lib\router\route.js:137:13)
at next (c:\projects\nodeMocker\node-mock-server\node_modules\express\lib\router\route.js:131:14)
at next (c:\projects\nodeMocker\node-mock-server\node_modules\express\lib\router\route.js:131:14)
at next (c:\projects\nodeMocker\node-mock-server\node_modules\express\lib\router\route.js:131:14)

The path c:\products#\GET....... should actually be c:\projects\nodeMocker\node-mock-server\demo..... It seems that the full path is not taken on windows when running locally and moving it to the default path instead.

After some debugging it turns out to be the package itself in MockController.js. It assumes that the whole path is using forward slashes while on Windows, a local path is built with backward slashes in stead.

This issue is - by the way - not limited to /products only but any route when running locally.

Question: POST body with "params" key

Hello,

I have a POST request with a body like:

{
  "method": "DEL",
  "params": {
    "application": "LOANS",
    "record_id": "LD111111111111"
  }
}

My response should be something like:

{
    "record_id": "<%-getId(params);%>",
    "operation_successful": true
}

My getId function is:

....
getId: function ( params ) {
        return params.application;
    }
....

It seems to me that "params" is a reserved word for GET url parameters. So "params" has a value of empty object {} in getId function. How can I access "application" value in getId?

Best regards!

How to configure 500er response?

Hi smollweide,

I am struggling with the configuration of node-mock-server. I want to mock various HTTP responses (500, 409, 404, 400, 201, 200 etc). Unfortunately I can't understand the documentation on that part. I understand, that you can create files like error.<code>.json. But how do i invoke the node-mock-server to respond with the responses other than 400, 200 and the contents of the success.json but the content of the specific error.<code>.json?

Make automatic open an option

Currently opening can only be suppressed by running the mock server with NODE_ENV = 'test'. Please make that an official option (sth. like options: {open: true}) so that the behaviour can be controlled via configuration or when calling mockServer().

The use case is: once the node-mock-server has opened a ui, it should be possible to run it multiple times without ending up with numerous ui tabs. Opening by default is fine.

Navigates to root after adding new resource

I have created a custom URL path for the ui using uiPath: '/ui'. I use node-mock-server to serve my app resources at /.

After adding a new resource through the +Add button the application navigates to /, i.e. instead of the newly added resource I see my application.

The UI should navigate back to /ui instead.

Change schema structure to a response like structure

Currently a schema is structured like this:

"price": {
  "type": "object",
  "properties": {
    "currency": "string",
    "price": {
      "type": "object",
      "properties": {
        "value": {
          "type": "number"
        }
      }
    }
  }
}

Which is not really readable.

Better would be a structure like this:

"price": {
  "currency": "string",
  "price": {
    "value": {
      "type": "number"
    }
  }
}
  • adapt DTO Tests
  • adapt DTO write method
  • adapt Schema Tests
  • adapt Schema write method
  • adapt validation

hello world example with some data

Currently it is very difficult to evaluate the project. It's great to have a complex demo covering all the features. What would also be nice is to have another simple demo just serving some sample data. That will allow newcomers to start quickly and with time start using more advanced features.

Ignore and delete .store.json files

The server touches these files frequently and they get in the way when I switch between branches since I have to revert them all the time.

Hook after server startup?

I childprocess.fork a node-mock-server instance in the rollup plugin. It would be helpful to know when nms has come up, so I can open the application in the browser after the server is up. Is there such a hook already or would you accept a PR to process.send() a message back to the parent process after the server has started?

Different success files for different params

Call: /rest/v1/test/{id}

success.json

<%
    var data = {};

    switch (params.id) {
        case '1':
            data = response.success1;
            break;
        case '2':
            data = response.success2;
            break;
        default:
            data = response.success-default;
            break;
    }
%>

<%-JSON.stringify(data);%>

As requested by @JonWallsten

ReST responses that are not json

I tried to create a success.html containing an html fragment instead of json and use the radiobutton to select it. The response was empty and the log showed that response.txt was set to success.html, but an error stating that success.json could not be found.

Ideally, it should consider the Accept request header, so it would be possible to choose 'success' (not success. html), then request always the same resource and get success.json when Accept:application/json was requested, success.xml for application/xml, success.html for text/html etc.

If you are ok with that approach, you can assign me :-)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.