Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

scenario-mock-server

Package Overview
Dependencies
Maintainers
1
Versions
5
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

scenario-mock-server

Mock server powered by scenarios

  • 1.0.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
5.2K
increased by90.65%
Maintainers
1
Weekly downloads
 
Created
Source

Scenario Mock Server

Mock server powered by scenarios.

Table of contents

Installation

npm install scenario-mock-server

Example usage

const { run } = require('scenario-mock-server');

run({
	scenarios: {
		item: [
			{
				path: '/api/test-me',
				method: 'GET',
				response: { data: { blue: 'yoyo' } },
			},
		],
		cheese: [
			{
				path: '/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 select a scenario. The first declared scenario will be initially selected. In this case, enabling cheese will modify /api/test-me so that it returns { blue: 'cheese' }.

By default Scenario Mock Server runs in server mode storing the current selected scenario and context in server memory. Alternatively you can set cookieMode to true in the options, which stores the current scenario and context in a cookie instead. This is useful when you want to run a central mock server, but allow each user to select and store their own scenarios and associated contexts without it affecting other users.

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 = {
	path: '/some-path',
	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' } };
	},
};

Running tests in parallel

Scenario Mock Server aims for mock data to be readily available while you're devloping locally, but also when you're running your tests.

The default behaviour of Scenario Mock Server is to run with one scenario active at a time. However, this falls down if you want to use multiple scenarios at the same time when running your tests in parallel. This is where 2 custom headers will become useful: sms-scenario-id and sms-context-id.

Note: These headers are not currently supported in cookieMode.

sms-scenario-id header

When this header is set to the scenario id of choice, regardless of what the current scenario is set to in the server, all responses will behave as if this was the currently set scenario instead.

sms-context-id header

This header must also be set when context is being used, otherwise context will reset on each call to the server when using the sms-scenario-id header.

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, selectScenarioPath, scenariosPath, cookieMode, parallelContextSize } | defaults to {}

PropertyTypeDefaultDescription
portnumber3000Port that the http server runs on.
uiPathstring/Path that the UI will load on. http://localhost:{port}{uiPath}
selectScenarioPathstring/select-scenarioAPI path for selecting a scenario. http://localhost:{port}{selectScenarioPath}
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
parallelContextSizenumber10How large to make the number of contexts that can run in parallel. See Running tests in parallel

Types

Mock

HttpMock | GraphQlMock

See HttpMock and GraphQlMock for more details.

HttpMock

{ path, method, response }

PropertyTypeDefaultDescription
pathstring / 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

{ path, method, operations }

PropertyTypeDefaultDescription
pathstringrequiredPath 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.

Keywords

FAQs

Package last updated on 13 Mar 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc