10.0.1 • Published 1 year ago

data-mocks-server v10.0.1

Weekly downloads
251
License
MIT
Repository
github
Last release
1 year ago

Data Mocks Server

This package was originally a port of https://github.com/ovotech/data-mocks that prefers spinning up an express server instead of mocking out fetch and XHR operations. Thanks goes to grug for his idea and implementation.

Table of contents

Installation

npm install data-mocks-server

Example usage

const { run } = require('data-mocks-server');

run({
  default: [
    {
      url: '/api/test-me',
      method: 'GET',
      response: { data: { blue: 'yoyo' } },
    },
  ],
  scenarios: {
    cheese: [
      {
        url: '/api/test-me',
        method: 'GET',
        response: { data: { blue: 'cheese' } },
      },
    ],
  },
});

Calls to http://localhost:3000/api/test-me will start by returning { blue: 'yoyo' }.

Visiting http://localhost:3000 will allow you to Modify scenarios. The default response will always be included unless a scenario overrides it. In this case enabling cheese will modify /api/test-me so that it returns { blue: 'cheese' }.

API

createExpressApp

Returns the internal express instance

function({ default, scenarios, options })

run

Returns an http server, with an additional kill method

function({ default, scenarios, options })

default

Array<Mock> | { context, mocks } | required

PropertyTypeDefaultDescription
contextobjectundefinedUsed to set up data across API calls.
mocksArray<Mock>requiredSee Mock for more details.

scenarios

{ [scenarioName]: Array<Mock> | { group, mocks } }

PropertyTypeDefaultDescription
scenarioNamestringrequiredName of scenario.
MockMockrequiredSee Mock for more details.
groupstringundefinedUsed to group scenarios together so that only one scenario in a group can be selected.
contextobjectundefinedUsed to set up data across API calls.
mocksArray<Mock>requiredSee Mock for more details.

options

{ port, uiPath, modifyScenariosPath, resetScenariosPath, scenariosPath } | defaults to {}

PropertyTypeDefaultDescription
portnumber3000Port that the http server runs on.
uiPathstring/Path that the UI will load on. http://localhost:{port}{uiPath}
modifyScenariosPathstring/modify-scenariosAPI path for modifying scenarios. http://localhost:{port}{modifyScenariosPath}
resetScenariosPathstring/reset-scenariosAPI path for resetting scenarios. http://localhost:{port}{resetScenariosPath}
scenariosPathstring/scenariosAPI path for getting scenarios. http://localhost:{port}{scenariosPath}
cookieModebooleanfalseWhether or not to store scenario selections in a cookie rather than directly in the server

Types

Mock

HttpMock | GraphQlMock

See HttpMock and GraphQlMock for more details.

HttpMock

{ url, method, response }

PropertyTypeDefaultDescription
urlstring / RegExprequiredPath of endpoint. Must start with /.
method'GET' / 'POST' / 'PUT' / 'DELETE' / 'PATCH'requiredHTTP method of endpoint.
responseundefined / Response / HttpResponseFunctionundefinedResponse, HttpResponseFunction.

Response

{ status, headers, data, delay }

PropertyTypeDefaultDescription
statusnumber200HTTP status code for response.
headersobject / undefinedSee descriptionKey/value pairs of HTTP headers for response. Defaults to undefined when response is undefined, adds 'Content-Type': 'application/json' when response is not undefined and Content-Type is not supplied.
datanull / string / objectundefinedResponse data
delaynumber0Number of milliseconds before the response is returned.

HttpResponseFunction

function({ query, body, params, context, updateContext }): response | Promise<response>

PropertyTypeDefaultDescription
queryobject{}query object as defined by express.
bodyobject{}body object as defined by express.
paramsobject{}params object as defined by express.
contextobject{}Data stored across API calls.
updateContextFunctionpartialContext => updatedContextUsed to update context. partialContext can either be an object or a function (context => partialContext).
responseundefined / ResponserequiredResponse.

GraphQlMock

{ url, method, operations }

PropertyTypeDefaultDescription
urlstringrequiredPath of endpoint.
method'GRAPHQL'requiredIndentifies this mock as a GraphQlMock.
operationsArray<Operation>requiredList of operations for GraphQL endpoint. See Operation for more details.

Operation

{ type, name, response }

PropertyTypeDefaultDescription
type'query' / 'mutation'requiredType of operation.
namestringrequiredName of operation.
responseundefined / GraphQlResponse / GraphQlResponseFunctionundefinedGraphQlResponse, GraphQlResponseFunction.

GraphQlResponse

{ status, headers, data, delay }

PropertyTypeDefaultDescription
statusnumber200HTTP status code for response.
headersobject / undefinedSee descriptionKey/value pairs of HTTP headers for response. Defaults to undefined when response is undefined, adds 'Content-Type': 'application/json' when response is not undefined and Content-Type is not supplied.
data{ data?: null / object, errors?: array }undefinedResponse data
delaynumber0Number of milliseconds before the response is returned.

GraphQlResponseFunction

function({ variables, context, updateContext }): response | Promise<response>

PropertyTypeDefaultDescription
variablesobject{}variables sent by client.
contextobject{}Data stored across API calls.
updateContextFunctionpartialContext => updatedContextUsed to update context. partialContext can either be an object or a function (context => partialContext).
responseundefined / GraphQlResponserequiredGraphQlResponse.

Allowing for multiple responses

Sometimes you may want an endpoint to respond with different status codes depending on what is sent. It is the recommendation of this package that this can be achieved by using scenarios. However, given response can be a function, it is possible to respond with a different value for the status, headers, data and delay properties:

const mock = {
  url: '/some-url',
  method: 'GET',
  response: ({ body }) => {
    if (body.name === 'error1') {
      return {
        status: 400,
        data: { message: 'something went wrong' },
        delay: 1000,
      };
    }

    if (body.name === 'error2') {
      return {
        status: 500,
        data: { message: 'something else went wrong' },
        delay: 2000,
      };
    }

    if (body.name === 'notFound') {
      return {
        status: 404,
        data: { message: 'no data here' },
      };
    }

    // Default status is 200
    return { data: { message: 'success' } };
  },
};
10.0.0

1 year ago

10.0.1

1 year ago

9.3.2

1 year ago

9.3.1

1 year ago

9.3.0

1 year ago

9.1.2

2 years ago

9.2.0

2 years ago

9.1.1

3 years ago

9.1.0

3 years ago

9.0.1

3 years ago

9.0.0

3 years ago

8.3.0

3 years ago

8.1.0

4 years ago

8.2.0

4 years ago

8.0.1

4 years ago

8.0.0

4 years ago

7.0.0

4 years ago

5.6.0

4 years ago

5.5.0

4 years ago

6.0.1

4 years ago

6.0.0

4 years ago

5.6.1

4 years ago

5.4.2

4 years ago

5.4.1

4 years ago

5.4.0

4 years ago

5.3.1

4 years ago

5.3.0

4 years ago

5.2.1

4 years ago

5.2.0

4 years ago

5.1.0

4 years ago

5.0.1

4 years ago

5.0.0

4 years ago

4.0.3

4 years ago

4.0.2

5 years ago

4.0.1

5 years ago

4.0.0

5 years ago

3.4.2

5 years ago

3.4.1

5 years ago

3.4.0

5 years ago

3.3.1

5 years ago

3.3.0

5 years ago

3.2.1

5 years ago

3.2.0

5 years ago

3.1.2

5 years ago

3.1.1

5 years ago

3.1.0

5 years ago

3.0.0

5 years ago

2.2.1

5 years ago

2.2.0

5 years ago

2.1.0

5 years ago

2.0.1

5 years ago

2.0.0

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago