Giter Site home page Giter Site logo

mockserver's Introduction

Deprecation notice

This project is not under active maintenance (see #82)

Development is continued at https://github.com/fauxauldrich/camouflage

For details on how to port your existing projects please visit Camouflage Documentation, or post your questions in Camouflage's discussion

mockserver

Build Status

mockserver is a library that will help you mocking your APIs in a matter of seconds: you simply organize your mocked HTTP responses in a bunch of mock files and it will serve them like they were coming from a real API; in this way you can write your frontends without caring too much whether your backend is really ready or not.

Installation

Mockserver can be installed globally if you need to run it as a command:

$ npm install -g mockserver

$ mockserver -p 8080 -m test/mocks
Mockserver serving mocks under "test/mocks" at http://localhost:8080

or as a regular NPM module if you need to use it as a library within your code:

npm install mockserver

then in your test file:

var http = require('http');
var mockserver = require('mockserver');

http.createServer(mockserver('path/to/your/mocks')).listen(9001);

This will run a simple HTTP webserver, handled by mockserver, on port 9001.

At this point you can simply define your first mock: create a file in path/to/your/mocks/example-response called GET.mock:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8

{
   "Random": "content"
}

If you open your browser at http://localhost:9001/example-response you will see something like this:

example output

And it's over: now you can start writing your frontends without having to wait for your APIs to be ready, or without having to spend too much time mocking them, as mockserver lets you do it in seconds.

Verbosity

By default mockserver is running in verbose mode: log messages are pushed to stdout. That will help to distinguish, which mock file matches best the request.

$ mockserver -p 8080 -m './mocks'
Mockserver serving mocks {verbose:true} under "./mocks" at http://localhost:8080
Reading from ./mocks/api/GET--a=b.mock file: Not matched
Reading from ./mocks/api/GET.mock file: Matched

Option -q|--quiet disables this behavior.

Mock files

As you probably understood, mock files' naming conventions are based on the response that they are going to serve:

$REQUEST-PATH/$HTTP-METHOD.mock

For example, let's say that you wanna mock the response of a POST request to /users, you would simply need to create a file named POST.mock under users/.

The content of the mock files needs to be a valid HTTP response, for example:

HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8

{
   "Accept-Language": "en-US,en;q=0.8",
   "Host": "headers.jsontest.com",
   "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
   "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
}

Check our own mocks as a reference.

Custom Headers

You can specify request headers to include, which allows you to change the response based on what headers are provided.

To do this, you need to let mockserver know which headers matter, by exposing comma-separated environment MOCK_HEADERS variable, like so:

$ MOCK_HEADERS=x-foo,authorization mockserver -m . -p 9001

Or by setting the headers array on the mockserver object, like so:

var mockserver = require('mockserver');
mockserver.headers = ['Authorization', 'X-My-Header'];

Any headers that are set and occur within the array will now be appended to the filename, immediately after the HTTP method, like so:

GET /hello
Authorization: 12345

hello/GET_Authorization=12345.mock
GET /hello
X-My-Header: cow
Authorization: 12345

hello/GET_Authorization=12345_X-My-Header=cow.mock

Note: The order of the headers within the headers array determines the order of the values within the filename.

The server will always attempt to match the file with the most tracked headers, then it will try permutations of headers until it finds one that matches. This means that, in the previous example, the server will look for files in this order:

hello/GET_Authorization=12345_X-My-Header=cow.mock
hello/GET_X-My-Header_Authorization=12345=cow.mock
hello/GET_Authorization=12345.mock
hello/GET_X-My-Header=cow.mock
hello/GET.mock

The first one matched is the one returned, favoring more matches and headers earlier in the array.

The headers array can be set or modified at any time.

Response Delays

When building applications, we cannot always guarantee that our users have a fast connection, which is latency free. Also some HTTP calls inevitably take more time than we'd, like so we have added the ability to simulate HTTP call latency by setting a custom header

Response-Delay: 5000

The delay value is expected in milliseconds, if not set for a given file there will be no delay.

Query string parameters and POST body

In order to support query string parameters in the mocked files, replace all occurrences of ? with --, then append the entire string to the end of the file.

GET /hello?a=b

hello/GET--a=b.mock
GET /test?a=b&c=d?

test/GET--a=b&c=d--.mock

(This has been introduced to overcome issues in file naming on windows)

To combine custom headers and query parameters, simply add the headers then add the parameters:

GET /hello?a=b
Authorization: 12345

hello/GET_Authorization=12345--a=b.mock

Similarly, you can do the same thing with the body of a POST request: if you send Hello=World as body of the request, mockserver will look for a file called POST--Hello=World.mock

In the same way, if your POST body is a json like {"json": "yesPlease"}, mockserver will look for a file called POST--{"json": "yesPlease"}.mock. Warning! This feature is NOT compatible with Windows. This is because Windows doesn't accept curly brackets as filenames.

If no parametrized mock file is found, mockserver will default to the nearest headers based .mock file

ex:

GET /hello?a=b
Authorization: 12345

if there's no hello/GET_Authorization=12345--a=b.mock, we'll default to hello/GET_Authorization=12345.mock or to hello/GET.mock

Wildcard slugs

If you want to match against a route with a wildcard - say in the case of an ID or other parameter in the URL, you can create a directory named __ as a wildcard.

For example, let's say that you want mock the response of a GET request to /users/:id, you can create files named users/1/GET.mock, users/2/GET.mock, users/3/GET.mock, etc.

Then to create one catchall, you can create another file users/__/GET.mock. This file will act as a fallback for any other requests:

ex:

GET /users/2

GET /users/2/GET.mock

ex:

GET /users/1000

GET /users/__/GET.mock

ex:

GET /users/1000/detail

GET /users/__/detail/GET.mock

Custom imports

Say you have some json you want to use in your unit tests, and also serve as the body of the call. You can use this import syntax:

HTTP/1.1 200 OK
Content-Type: application/json

#import './data.json';

whereby ./data.json is a file relative to the including mock file. You can have as many imports as you want per mock file.

You can also import javascript modules to create dynamic responses:

// script.js
module.exports = {
  id: Math.random()
    .toString(36)
    .substring(7),
  date: new Date(),
};

Then import the file as above #import './script.js'

Dynamic values of headers can be filled with valid JS statements such as:

X-Subject-Token: #header ${require('uuid/v4')()};

Custom response status

You can specify response status (200, 201, 404. etc.) depending on request parameters. To do this, you need to use #import './code.js'; in first line of your mock file:

#import './code.js';
Content-Type: application/json; charset=utf-8
Access-Control-Allow-Origin: *

{
 "Random": "Content" 
}

You import javascript modules to create dynamic code responses:

// code.js
module.exports = request.body.indexOf('foo') !== -1 ? 'HTTP/1.1 200 OK' : 'HTTP/1.1 400 Bad request'

Tests

Tests run on travis, but if you wanna run them locally you simply have to run mocha or its verbose cousin ./node_modules/mocha/bin/mocha (if you don't have mocha installed globally).

To run test with debug output, expose DEBUG=true environment variable:

$ DEBUG=true ./node_modules/mocha/bin/mocha

Or as npm shortcut:

$ DEBUG=true npm test

mockserver's People

Contributors

ariutta avatar christianrondeau avatar cirpo avatar denis-zavgorodny avatar dependabot[bot] avatar difelice avatar gordeevbr avatar jaymecd avatar jeremywaller avatar kolbii avatar maraisr avatar odino avatar overzealous avatar r-a-j-s avatar shubhendumadhukar avatar tmahesh avatar unlucio avatar vitalybe avatar wheeyls 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mockserver's Issues

gulp support?

Hello,

How do I suppose to embed this inside Gulp ( v4 preferably ) .

Also how to enable access log , preferably inside gulp terminal

Here is my code inside the task block

return http.createServer(mockserver('mocks')).listen(9090);

It works but the integration is not so good
Thanks

npm install fails on windows

On Windows 7:
"npm install -D mockserver"

npm ERR! Error: ENOENT: no such file or directory, open 'C:\myProject\node_modules\mockserver\test\mocks\return-200\POST--{"json": "yesPlease"}.mock'

I think it is because Windows doesn't like the quotes in the file name.

Is it possible to use the wildcards for the parameter?

In the documentation, I did not manage to find the wildcards for the parameter.
For example, I want to have the following test case:
the definition: GET--type=__&location=__.mock
the expected behavior: have a response for GET method with any type and location.

I can contribute to this case.

Thank you in advance.

JSON payloads

When posting JSON in the body, the filename matcher attempts to match the entire body of the payload as the filename.

This has some repercussions on windows as many characters are invalid:

Reading from mocks/POST--{"data":{"index":0,"max":25},"sortBy":["name"]}.mock file: Not matched

I wonder if there are any alternative ways to match responses to requests?

Is this still actively maintained?

Is this library still being actively maintained? I see 4 open pr's with one all the way back from March.

It seems like there's enough activity here that we could find a new maintainer or find some help for the existing maintainers if needed.

@odino has some more recent commits. Perhaps, they know the status of the project?

#import feature not working

Hello,
while having fun with the tool, I've found some issue. I've created very simple mock file:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8

#import './data.json'

Unfortunately, instead of having data.json file's content inserted as body of response, this is what is actually returned to the client:
image

mockserver v1.11.0
node v8.1.3

Wildcard extended test - is it correct?

Hello!
I am trying to use wildcards. To understand I have executed the test from this repo.
What I have found is that it does not work as it is expected (IMO).

When I put this URL "http://localhost:9001//wildcard-extended/__/foobar" then I get correct response "wildcards-extended".
But when I put "http://localhost:9001//wildcard-extended/1/foobar" then I get "Not Mocked".

Is it correct behavior?
What I have to do to not make copies of the same mock file if I want to have following structure:

foo/1/bar/GET.mock
foo/2/bar/GET.mock
...

Regular Expression Invalid

Mockserver serving mocks {verbose:true} under "mockapi" at http://localhost:8080 Reading from mockapi\trials\GET.mock file: Matched C:\Users\arunn3\AppData\Roaming\npm\node_modules\mockserver\mockserver.js:17 const regex = /(?<=HTTP\/\d.\d\s{1,1})(\d{3,3})(?=[a-z0-9\s]+)/gi; ^

SyntaxError: Invalid regular expression: /(?<=HTTP\/\d.\d\s{1,1})(\d{3,3})(?=[a-z0-9\s]+)/: Invalid group at parseStatus (\AppData\Roaming\npm\node_modules\mockserver\mockserver.js:17:17) at Monad.map (\AppData\Roaming\npm\node_modules\mockserver\monad.js:4:25) at parse (\AppData\Roaming\npm\node_modules\mockserver\mockserver.js:85:6) at (\AppData\Roaming\npm\node_modules\mockserver\mockserver.js:389:22 at IncomingMessage.<anonymous> (\AppData\Roaming\npm\node_modules\mockserver\mockserver.js:281: 5) at emitNone (events.js:106:13) at IncomingMessage.emit (events.js:208:7) at endReadableNT (_stream_readable.js:1056:12) at _combinedTickCallback (internal/process/next_tick.js:138:11) at process._tickCallback (internal/process/next_tick.js:180:9)

I tried the regular expression /(?<=HTTP/\d.\d\s{1,1})(\d{3,3})(?=[a-z0-9\s]+)/gi and it works ; the mock content I used is as below :
HTTP/1.1 200 OK Content-Type: application/json;charset=utf-8 { "Random": "content" }

What is wrong here ???

Multiple headers with the same name are not supported

HTTP allows for multiple headers to be sent with the same name, for example:

Access-Control-Expose-Headers: accept
Access-Control-Expose-Headers: authorization
Access-Control-Expose-Headers: content-type
Access-Control-Expose-Headers: content-length
Access-Control-Expose-Headers: origin
Access-Control-Expose-Headers: tr-client
Access-Control-Expose-Headers: tr-admin
Access-Control-Expose-Headers: dnt
Access-Control-Expose-Headers: Content-Disposition

Such response can not be reproduced by mockserver. I suggest that headers should be represented as an array of name and value pairs, not a map.

Any way to serve binary content types such as PDF?

Just found this and it's so easy to use! I was wondering how easy it is to mock non-ascii content types. I played with mocks using PDF content with the following headers

HTTP/1.1 200 OK
Content-Type: application/pdf

followed by a blank line and then the PDF content but it rendered an empty PDF content. Only 200+ bytes were sent. Wondering if anyone's encountered that before?

Rightmost wilcard not matched first

Files:
mocks\app\rest\v1\masterdata\article_\GET.mock
mocks\app\rest\v1\masterdata\article\gtin_
\GET.mock

Expected:
Reading from mocks\app\rest\v1\masterdata\article\gtin\123\GET.mock Matched

Actual:
Reading from mocks\app\rest\v1\masterdata\article\gtin\123\GET.mock file: Not matched
Reading from mocks\app\rest\v1\masterdata\article__\GET.mock file: Matched

Wrong arguments passed to the `evalHandler`

Passing the context to evalHandler (contrary to its signature) makes the request parameter unreachable in the evaluated code.

module.exports = function evalHandler(value, request) {

.map((value) => evalHandler(value, context, request))

.map((value) => evalHandler(value, context, request))

So the following doesn't work, since request has here the value of context instead:

#eval request.body;

Nested wildcards are not working

I'm trying to mock the following call:

GET api/namespaces/my-namespace/services/my-service/metrics

I tried the following file:
api/namespaces/__/services/__/metrics/GET.mock and is not working, the server answers: "Not Mocked"

However this works: api/namespaces/__/services/my-service/metrics/GET.mock

It makes me believe that nesting the wilcards is not working (or not yet implemented).

Parallell calls does not seem to be supported

Mockserver doesnt seem to support parallell calls correctly. If I create a mock using the mock file below containing response delay = 5000, the expected behaviour is that the call response time should be 5 sec. This works fine with only performing one single call. However, if 2 calls are being performed in the same time, the first call will get 5 sec response time, but the other will get response time close 10 sec (2 * 5).

The reason for this is likely that Mockserver doesnt have support to handle concurrent calls. The documentation doesnt mention if this is intended or not, so it is unclear if this is out of scope for the tool, or ifs a bug

Security - Deprecated [email protected]: Please upgrade to version 7 or higher.

A project uses the mock server latest version and when we perform the npm install, it triggers the following messages.

npm WARN deprecated [email protected]: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.

Could you please upgrade uuid artefact ?. https://www.npmjs.com/package/**express-request-id** is at the version 3.0! on today.

Thank you.

+-- @mocks-server/[email protected]
| +-- @mocks-server/[email protected]
| | +-- @babel/[email protected]
| | | +-- @ampproject/[email protected] deduped
| | | +-- @babel/[email protected] deduped
| | | +-- @babel/[email protected] deduped
| | | +-- @babel/[email protected] deduped
| | | +-- @babel/[email protected] deduped
| | | +-- @babel/[email protected] deduped
| | | +-- @babel/[email protected] deduped
| | | +-- @babel/[email protected] deduped
| | | +-- @babel/[email protected] deduped
| | | +-- @babel/[email protected] deduped
| | | +-- [email protected] deduped
| | | +-- [email protected] deduped
| | | +-- [email protected] deduped
| | | +-- [email protected] deduped
| | | -- [email protected] deduped | | +-- @babel/[email protected] | | | +-- @babel/[email protected] deduped | | | +-- [email protected] | | | | +-- [email protected] | | | | | -- [email protected]
| | | | +-- [email protected]
| | | | -- [email protected] | | | | -- [email protected] deduped
| | | +-- [email protected]
| | | | +-- [email protected]
| | | | +-- [email protected] deduped
| | | | -- [email protected] | | | | -- [email protected]
| | | | -- [email protected] | | | | +-- [email protected] | | | | | -- [email protected]
| | | | | -- [email protected] | | | | -- [email protected]
| | | +-- [email protected]
| | | | +-- [email protected]
| | | | -- [email protected] | | | +-- [email protected] | | | -- [email protected]
| | | +-- [email protected]
| | | -- [email protected] deduped | | +-- @hapi/[email protected] | | | -- @hapi/[email protected]
| | +-- @mocks-server/[email protected]
| | | +-- [email protected] deduped
| | | +-- [email protected] deduped
| | | +-- [email protected]
| | | +-- [email protected]
| | | | +-- @types/[email protected]
| | | | +-- [email protected] deduped
| | | | +-- [email protected]
| | | | | +-- @babel/[email protected] deduped
| | | | | +-- [email protected]
| | | | | | -- [email protected] | | | | | +-- [email protected] | | | | | -- [email protected]
| | | | +-- [email protected]
| | | | -- [email protected] deduped | | | +-- [email protected] deduped | | | +-- [email protected] deduped | | | +-- [email protected] deduped | | | -- [email protected] deduped
| | +-- @mocks-server/[email protected]
| | | +-- [email protected]
| | | | +-- [email protected]
| | | | | -- [email protected] | | | | | -- [email protected]
| | | | -- [email protected] | | | | -- [email protected]
| | | +-- [email protected] deduped
| | | -- [email protected] deduped | | +-- @mocks-server/[email protected] | | +-- [email protected] | | | +-- [email protected] deduped | | | +-- [email protected] | | | +-- [email protected] | | | -- [email protected] deduped
| | +-- [email protected]
| | | +-- @babel/[email protected] deduped
| | | +-- @humanwhocodes/[email protected]
| | | +-- [email protected] deduped
| | | +-- [email protected]
| | | | +-- [email protected]
| | | | | -- [email protected] | | | | | -- [email protected]
| | | | -- [email protected] | | | | -- [email protected]
| | | +-- [email protected]
| | | -- [email protected] | | +-- [email protected] deduped | | +-- [email protected] | | | +-- [email protected] | | | -- [email protected] deduped
| | +-- [email protected] deduped
| | +-- [email protected]
| | | `-- [email protected]

Support the use of space in file names instead of the UriEncoded format

Currently, if i have to mock a request with query parameter value that includes a space, i have to create the mock file something like this:

GET hello/ getMockedResponse--api=Hello%20World.mock

What would be great is if we can use literal 'space' instead, like

GET hello/ getMockedResponse--api=Hello World.mock

Headers should not be case sensitive

Or at least if they are going to be case sensitive they should match what is put into the headers array and not be force camel cased.

When I do
mockServer.headers = ['x-b3-traceid']
Mockserver changes it to
Reading from test/mockserver/myservice/POST_X-B3-Traceid=traceValue.mock

OPTIONS Calls

I am doing http OPTIONS call to the mocked-api via a browser using axios. I created a OPTIONS.mock file which is in the same directory a my POST.mock (this is working), but unfortunately this does not match. Do you have any idea how I can solve this?

Reading from mocks/1.0/auth/OPTIONS.mock file: Not matched

Path after wildcard not recognized

mockserver 3.0.0

file:

foo/__/bar/GET.mock

request:

/foo/1/bar

expected server output:

Reading from foo/1/bar/GET.mock file: Not matched
Reading from foo/__/bar/GET.mock file: Matched

got:

Reading from foo/1/bar/GET.mock file: Not matched
Reading from foo/__/GET.mock file: Not matched

Using absolute path to the mocks directory fails for custom imports

Running test mockserver/mockserver()/should be able to handle imports with an absolute path to the mocks directory:

var mocksDirectory = path.join(__dirname, './mocks');

fails with

Error: ENOENT: no such file or directory, open 'Users/christianjacobsen/dev/mockserver/test/mocks/import/data.json'

Bump Version in package.json

Need to bump the package version & republish, it still is marked as 0.8.0. (The easiest way is to run npm version 0.10.1 && npm publish if you don't already know this.)

Extend support of wildcard directories

The wildcard feature merged in #37 has been a great in project I'm working on, but it only supports wildcards at the end of a path (i.e. '/resource//GET.mock'). I have a use case where the resource id is in the middle of a path (i.e. '/resource//foobar/GET.mock').

I have a fix running locally to support this use case. Are you open to a pull request?

Parameter path for import

Hello,

It could be very interesting to have the possibilites to have dynamic file import with the queried path:

Query: http://localhost:8000/articles/1

My mock file: /mocks/__/GET.mock

HTTP/1.1 200 OK
Content-Type: application/json

#import `${request.url.split('/')[2]+".json"}`;

I try this:

module.exports = (() => {
    var fs = require('fs');
    var obj = JSON.parse(fs.readFileSync("./"+request.url.split('/')[2]+".json", 'utf8'));
    return obj;
})();

But relative path doesn't work, and i'm not fan to put an absolute path here, but it works

Do you have a solution ?

Thanks for all :-)

Any way to handle changing session ids in ajax requests?

As per the instructions, I have made a folder structure in line with the request paths. Can you suggest any way to work around with session ids inserted in between the paths?

Like for request path \license-manager\lm\v2\catalog\specifications\vendors the actual request is made like \license-manager\0e8a2883-df5d-42aa-9d84-2b02137ef479\lm\v2\catalog\specifications\vendors

It won't be possible to make a folder with a fixed session id. Can you suggest any workaround for this? Like setting a fixed session id every time? or anything else?

The request are being made through an extjs application.

Question: how to mock png responses?

Is it possible to mock html pages with png images?
I've managed to mock the html pages, but the images do not appear. The images are in the response's mock folder.
My first guess is that the image response needs to be mocked as well.

JSON Object not getting returned in response

I'm trying to return a json object but there is no response data coming back. It works fine over postman but not when using axios. Can someone help me with this?

My frontend code looks like this:-

export const getCollaborator = (collaboratorID, dispatch) => {
  axios
    .get(`http://localhost:8081/collaborators/${collaboratorID}`,
    {
      headers:{
        "Accept": "application/json"
      }
    })
    .then(
      // success
      ({ data, status }) => {
        console.log("status", status);
        
        return dispatch({
          type: GET_COLLABORATOR,
          payload: data
        });
      }
    ).catch(error => {
      if (error.response) {
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx
        console.log(error.response.data);
        console.log(error.response.status);
        console.log(error.response.headers);
      } else if (error.request) {
        // The request was made but no response was received
        // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
        // http.ClientRequest in node.js
        console.log(error.request);
      } else {
        // Something happened in setting up the request that triggered an Error
        console.log('Error', error.message);
      }
      console.log('====================================');
      console.log(error);
      console.log('====================================');
      console.log(error.config);
    });
};

And the mock file:-

HTTP/1.1 200 OK
Content-Type: application/json

#import './data.json';

data.json:-

{
  "collaborator_id": 1,
  "username": "[email protected]",
  "profile_desc": "I am amazing",
  "primary_expertise": 1,
  "secondary_expertise": 3,
  "primary_other": "",
  "secondary_other": "",
  "weblinks": [
    {
      "type": "personal",
      "url": "www.my-site.com"
    },
    {
      "type": "linkedIn",
      "url": "www.linkedIn.com"
    }
  ],
  "skills": [
    {
      "skill_name": "java",
      "skill_level": 1
    },
    {
      "skill_name": "React",
      "skill_level": 2
    },
    {
      "skill_name": "Python",
      "skill_level": 3
    }
  ],
  "education": [
    {
      "school_name": "Cambridge University",
      "country": 1,
      "qualification": "B. Sc.",
      "major": "1st Class",
      "year": 1999
    },
    {
      "school_name": "Oxford University",
      "country": 1,
      "qualification": "B. Sc.",
      "major": "1st Class",
      "year": 2000
    }
  ]
}

Middleware to add a root path to the app routes

Hi guys,

I just wanted to check if I can add a root path to all the express routes ?

In express, the similar can be achieved using the below code

app.use('/api/v1', allRoutes);

So basically, any route like /product/:id would become /api/v1/product/:id.

I tried doing something similar using middlewares but unfortunately it didnt work

  {
    id: 'root-path',
    url: '/api/v1',
    method: ["GET", "POST", "PUT", "PATCH"],
    variants: [
      {
        id: 'enabled',
        response: (req, res, next) => next(),
      },
    ],
  },

how to mock http 500 response object?

POST.mock:

HTTP/2 500
content-type: application/json;charset=UTF-8
access-control-allow-origin: *
Access-Control-Allow-Headers: authorization, content-type

{"code":"internal_error","message":"general error"}

// Expect response: {"code":"internal_error","message":"general error"}
// Actual response: undefined

POST.mock is not working

Hi,
I created a file POST.mock with below content in api folder
HTTP/1.1 200 OK
Content-Type: application/json

And then hit http://localhost:8080/api, it's throwing " Not Mocked"

In logs, it's always searching GET.mock file. Please assist me.

[email protected] start /Users/rabodevops-45/Personal/ReactJs/hello-world
concurrently "mockserver -p 8080 -m test/mocks" "react-scripts start"

[0] Mockserver serving mocks {verbose:true} under "test/mocks" at http://localhost:8080
[1] ℹ 「wds」: Project is running at http://10.240.125.7/
[1] ℹ 「wds」: webpack output is served from /
[1] ℹ 「wds」: Content not from webpack is served from /Users/rabodevops-45/Personal/ReactJs/hello-world/public
[1] ℹ 「wds」: 404s will fallback to /index.html
[1] Starting the development server...
[1]
[1] Compiled with warnings.
[1]
[1] ./src/Home/home.jsx
[1] Line 2:10: 'Route' is defined but never used no-unused-vars
[1] Line 3:10: 'MaterialEntryForm' is defined but never used no-unused-vars
[1]
[1] ./src/Header/header.jsx
[1] Line 5:5: 'Switch' is defined but never used no-unused-vars
[1] Line 6:5: 'Route' is defined but never used no-unused-vars
[1]
[1] Search for the keywords to learn more about each warning.
[1] To ignore, add // eslint-disable-next-line to the line before.
[1]
[0] Reading from test/mocks/api/GET.mock file: Not matched

CORS support?

I can't send request from my app which is running on localhost port 4200 to mock server (port 8080), is there any solution? Thanks!

ReferenceError: Atomics is not defined

Failure on node 8.9.4

Stacktrace ;
project-dir\node_modules\mockserver\mockserver.js:381
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, delay);
^
ReferenceError: Atomics is not defined

non json, customized response

I have the need to mock some xml responses, but make some changes to the content on the fly.
I can easily have the .mock file import a .js file that will, in turn, load and modify the xml.
the thing is, the importHandler.js file clearly states that

          if (importThisFile.endsWith('.js')) {
              return JSON.stringify(eval(content.toString()));

so my xml comes out as a json stringified string...

is there another way to go about this?

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.