# @tempworkssoftware/open-api-mocker

> Generate mock data for your application in a way that is maintainable and responsive to a changing API.

Latest version **1.1.1** (published 2025-08-14) · UNLICENSED license · 0 weekly downloads

## Install

```sh
npm install @tempworkssoftware/open-api-mocker
pnpm add @tempworkssoftware/open-api-mocker
yarn add @tempworkssoftware/open-api-mocker
bun add @tempworkssoftware/open-api-mocker
```

## Health

**Score 45/100 (D)** — status: stable.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

## Facts

| | |
|---|---|
| Version | 1.1.1 |
| Published | 2025-08-14 |
| First published | 2019-12-17 |
| Weekly downloads | 0 |
| License | UNLICENSED |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 10 |
| Unpacked size | 1.9 MB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Maintainers | twbenjoseph, matt.mathieson, tempworks-admin, dsandkamp |
| Keywords | mock, open api |

## Links

- npm: https://www.npmjs.com/package/@tempworkssoftware/open-api-mocker
- Homepage: https://tempworks-open-api-mocker.neocities.org/index.html
- npm.io page: https://npm.io/package/@tempworkssoftware/open-api-mocker

## Dependencies (10)

- [del](https://npm.io/package/del.md) ^6.0.0
- [sway](https://npm.io/package/sway.md) ^2.0.6
- [chance](https://npm.io/package/chance.md) ^1.1.7
- [lodash](https://npm.io/package/lodash.md) ^4.17.21
- [async-mutex](https://npm.io/package/async-mutex.md) ^0.3.1
- [object-hash](https://npm.io/package/object-hash.md) ^2.1.1
- [@babel/runtime](https://npm.io/package/@babel/runtime.md) ^7.13.10
- [json-schema-faker](https://npm.io/package/json-schema-faker.md) ^0.5.0-rcv.34
- [@types/json-schema](https://npm.io/package/@types/json-schema.md) ^7.0.7
- [strip-json-comments](https://npm.io/package/strip-json-comments.md) ^3.1.1

## Alternatives

- [pagerjs](https://npm.io/package/pagerjs.md) — 60 weekly downloads
- [whistle.savefor-mock](https://npm.io/package/whistle.savefor-mock.md) — 4 weekly downloads
- [@visant/psd-engine](https://npm.io/package/@visant/psd-engine.md) — 0 weekly downloads
- [tillage](https://npm.io/package/tillage.md) — 0 weekly downloads
- [rspack-plugin-mock](https://npm.io/package/rspack-plugin-mock.md) — 0 weekly downloads

## Recent versions

- 1.1.1 (latest) — 2025-08-14
- 1.1.0 — 2025-08-11
- 1.0.12 — 2024-01-31
- 1.0.11 — 2022-06-21
- 1.0.10 — 2022-04-15
- 1.0.9 — 2021-04-19
- 1.0.8 — 2020-04-30
- 1.0.7 — 2020-04-30
- 1.0.6 — 2020-02-06
- 1.0.5 — 2020-01-27
- 1.0.4 — 2020-01-08
- 1.0.3 — 2020-01-03
- 1.0.2 — 2019-12-24
- 1.0.1 — 2019-12-17
- 1.0.0 — 2019-12-17

## README

# Open API Mocker

Generate mock data for your application in a way that is maintainable and responsive to a changing API.

-   This library will consume one or more [Open API 2.0](https://swagger.io/docs/specification/2-0/basic-structure/) definitions, and then you can call the [`fetchMock`](https://tempworks-open-api-mocker.neocities.org/modules.html#fetchmock) function to generate a mock response for a given request.
-   The mock data will include random values from the [Chance](https://chancejs.com/) library. The random values will be generated based on a hash of the request. This means that if you make the same request more than once, you will receive the same response.
-   The structure of the mock data will conform to the provided Open API schema by default. If you'd like to make the data even more realistic, you can customize the constraints for how the mock responses are generated on a per-endpoint basis, or for all operations in an API at once.

## Installation

`npm install --save-dev @tempworkssoftware/open-api-mocker`

## Requirements

This library was written to support a product that uses the [Open API 2.0](https://swagger.io/docs/specification/2-0/basic-structure/) format, and is currently limited to that specification. In addition, each operation in an API definition must have a unique `operationId`, because it will be used as a variable name and as a folder name.

## Usage

### [`generateDescriptions`](https://tempworks-open-api-mocker.neocities.org/modules.html#generatedescriptions)

This library supports per-endpoint mock customization. This is made possible by generating files for each API operation that describe how to mock its response. To begin, call the [`generateDescriptions`](https://tempworks-open-api-mocker.neocities.org/modules.html#generatedescriptions) function from a Node environment:

```javascript
const oam = require('@tempworkssoftware/open-api-mocker');

await oam.generateDescriptions({
    apiDefinition: 'https://my-api.com/swagger.json', // Can be a URL, file path, or object
    outputPath: path.resolve(__dirname, 'myApiMocks'), // Where to put the mock response descriptions
});
```

This will produce the following file structure:

```
myApiMocks
│
└───GetProduct
│      defaultMockResponse_DONT_EDIT.json
│      extendMockResponse.js
│
└───PostProduct
│      defaultMockResponse_DONT_EDIT.json
│      extendMockResponse.js
│
└─── ...etc
```

There will be a folder for each API operation, containing two files. These two files together describe how to generate a mock response for the operation.

### `defaultMockResponse_DONT_EDIT.json`

-   Here is a simple example file:

    ```json
    {
        "status": 200,
        "bodySchema": {
            "type": "object",
            "properties": {
                "productId": {
                    "format": "int32",
                    "type": "integer",
                    "valueOfParameter": "productId"
                },
                "productName": {
                    "type": "string"
                },
                "description": {
                    "type": "string",
                    "chance": "sentence"
                }
            }
        }
    }
    ```

-   This file describes the structure of a successful response to this operation. It uses [JSON Schema](https://json-schema.org/) format, but allows some [additional properties](https://tempworks-open-api-mocker.neocities.org/modules.html#mockschemaspecialrules) which can further constrain how this mock response will be generated.
-   This file will be updated every time [`generateDescriptions`](https://tempworks-open-api-mocker.neocities.org/modules.html#generatedescriptions) is run, so you should not edit this file directly. If you would like to customize how this file is generated, you can do it in a way that will affect all operations in the API: Use the `getDefaultMockRules` callback that you can include in the [options](https://tempworks-open-api-mocker.neocities.org/modules.html#apigenerationoptions) passed to [`generateDescriptions`](https://tempworks-open-api-mocker.neocities.org/modules.html#generatedescriptions).

### [`extendMockResponse.js`](https://tempworks-open-api-mocker.neocities.org/modules.html#extendmockresponse)

-   Here is a simple example file:

    ```javascript
    /**
     * Function for manually describing mock data for the following API operation:
     * OperationId: GetProduct
     * HTTP Method: GET
     * Path: /products/{productId}
     *
     * @type {import('@tempworkssoftware/open-api-mocker').ExtendMockResponse}
     */
    // eslint-disable-next-line no-unused-vars
    const extendMockResponse = (parameters, utils) => {
        return {
            partialBody: {
                productName: 'Chocolate Frog',
            },
        };
    };

    export default extendMockResponse;
    ```

-   This file will not be overwritten when [`generateDescriptions`](https://tempworks-open-api-mocker.neocities.org/modules.html#generatedescriptions) is run, so feel free to edit it yourself. This file is your chance to customize the mock response in a way that will only affect this endpoint.
-   The function in this file will be called at runtime when processing a request for the API operation. Within this function, you have access to the operation parameters from the request.
-   You have various options for how to describe the response body in your return value:
    -   `partialBody`: The values you define here will be deeply merged with the the values generated from the `bodySchema` in `defaultMockResponse_DONT_EDIT.json` when generating the mock response.
    -   `bodySchema`: The partial schema you define here will be deeply merged with the `bodySchema` in `defaultMockResponse_DONT_EDIT.json` before generating the mock response.
    -   `body`: The actual response body returned for the request. If this is provided, `bodySchema` is ignored and `body` is used instead. Of course, using `body` will result in no randomness in the mock response.

### Example Mock Response

If the two example files above were used for the request `'GET /products/14'`, then the generated mock response might be:

```javascript
{
    status: 200,
    body: {
        productId: 14,
        productName: 'Chocolate Frog',
        description: 'Witpevze mappos isoletu fo res bi geow pofin mu rupoho revzi utva ne.',
    }
}
```

### [`configure`](https://tempworks-open-api-mocker.neocities.org/modules.html#configure)

Once all of the mock description files have been generated, you'll want to configure `open-api-mocker` for runtime operation. You'll want to do this once, before [`fetchMock`](https://tempworks-open-api-mocker.neocities.org/modules.html#fetchmock) is called. At the least, you'll need to tell `open-api-mocker` where your mock response description files are. When you ran [`generateDescriptions`](https://tempworks-open-api-mocker.neocities.org/modules.html#generatedescriptions), a file named `mockIndex.js` should have been created in your output directory. All you need to do is import that and pass it through to the [`configure`](https://tempworks-open-api-mocker.neocities.org/modules.html#configure) function:

```javascript
import oam from '@tempworkssoftware/open-api-mocker';
import mockApiIndex from './myApiMocks/mockIndex';

oam.configure({
    generatedMockApis: [
        {
            generatedMockApi: mockApiIndex,
        },
    ],
});
```

-   Note that if this will be run in the context of a browser, you will want to import from `@tempworkssoftware/open-api-mocker/dist/browser`.
-   There are a few more settings that you may find useful [here](https://tempworks-open-api-mocker.neocities.org/modules.html#settings). In particular, we needed the `useCaseSensitivePathAndParameterMatching` option.

### [`fetchMock`](https://tempworks-open-api-mocker.neocities.org/modules.html#fetchmock)

Once all of the mock description files have been generated and you've told `open-api-mocker` where to find them, you can make use of the [`fetchMock`](https://tempworks-open-api-mocker.neocities.org/modules.html#fetchmock) function to generate a mock response for a given request.

-   Note that if this will be run in the context of a browser, you will want to import from `@tempworkssoftware/open-api-mocker/dist/browser`.
-   Note that if a mock response isn't found, `undefined` will be returned. This gives you the flexibility to fall back however you deem appropriate.

```javascript
import { fetchMock } from '@tempworkssoftware/open-api-mocker';

const mockResponse = await fetchMock('https://my-api.com/products/14');
```

### Runtime mock overrides

You can programmatically override a mock for an operation. This is especially useful for making assertions about specific data within a test.

```javascript
import { mock, resetMock, fetchMock } from '@tempworkssoftware/open-api-mocker';

mock('GetProduct', {
    productId: 9,
    productName: 'Licorice Wand',
    description: 'A wand made of licorice.',
});

const mockResponse = await fetchMock('https://my-api.com/products/14');
const mockResponseBody = await mockResponse.json();
// mockResponseBody:
// {
//     productId: 9,
//     productName: 'Licorice Wand',
//     description: 'A wand made of licorice.'
// }

resetMock('GetProduct');
```

You can also partially override an operation mock from within a test. The values of the partialMock will be deeply merged with the values generated from the mock response description files.

```javascript
import { mock, resetMock, fetchMock } from '@tempworkssoftware/open-api-mocker';

partialMock('GetProduct', {
    productName: 'Licorice Wand',
});

const mockResponse = await fetchMock('https://my-api.com/products/14');
const mockResponseBody = await mockResponse.json();
// mockResponseBody:
// {
//     productId: 14,
//     productName: 'Licorice Wand',
//     description: 'Witpevze mappos isoletu fo res bi geow pofin mu rupoho revzi utva ne.',
// }

resetMock('GetProduct');
```

## API Reference

Please see the [API Reference](https://tempworks-open-api-mocker.neocities.org/modules.html) for more information about how to use this library.

## Contributing

TODO

### Use the following VSCode extensions

-   [ESLint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint)
-   [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode)

---
_Source: https://npm.io/package/@tempworkssoftware/open-api-mocker · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
