A cli tool to generate random mock data from OpenAPI definition for msw.

Overview

msw-auto-mock

GitHub Workflow Status npm

A cli tool to generate random mock data from OpenAPI descriptions for msw.

Why

We already have all the type definitions from OpenAPI spec so hand-writing every response resolver is completely unnecessary.

Usage

Install:

yarn add msw-auto-mock faker-js/faker -D

Read from your OpenAPI descriptions and output generated code:

# can be http url or a file path on your machine, support both yaml and json.
npx msw-auto-mock http://your_openapi.json -o ./mock.js

See here for Github API example. The msw mocking handlers was generated by following command:

npx msw-auto-mock https://raw.githubusercontent.com/github/rest-api-description/main/descriptions/ghes-3.3/ghes-3.3.json --output ./example/src/mock.js

Integrate with msw, see Mock Service Worker's doc for more detail:

# Install msw
yarn add msw --dev

# Init service worker
npx msw init public/ --save

Then import those mock definitions in you app entry:

import { startWorker } from './mock';

if (process.env.NODE_ENV === 'development') {
  startWorker();
}

Run you app then you'll see a successful activation message from Mock Service Worker in your browser's console.

Options

  • -o, --output: specify output file path or output to stdout.
  • -m, --max-array-length : specify max array length in response, it'll cost some time if you want to generate a huge chunk of random data.
  • -t, --match : specify keywords to match if you want to generate mock data only for certain requests, multiple keywords can be seperated with comma.
  • -h, --help: show help info.
Comments
  • fix: use setupServer to support Next.js

    fix: use setupServer to support Next.js

    • I added the following code to the template in order to support SSR with Next.js
    if (typeof window === 'undefined') {
      const { setupServer } = require('msw/node');
      const server = setupServer(...handlers);
      server.listen();
    } else {
      const worker = setupWorker(...handlers);
      worker.start();
    }
    
    • It's pretty much the same as the example from Next.js
    • Updated the version of faker.js and regenerated mock.js in /example
    opened by homerchen19 1
  • Can't work with faker v7

    Can't work with faker v7

    faker removed default export from v7.0.0 It's a breaking change, so the way of importing faker (https://github.com/zoubingwu/msw-auto-mock/blob/master/src/template.ts#L14) should be changed to import { faker } from '@faker-js/faker';. Otherwise it can't work with faker v7.

    opened by homerchen19 1
  • Suggestion: typescript, only handlers

    Suggestion: typescript, only handlers

    I am very impressed with the library, very useful.

    I had to implement it by adding a d.ts file in order to work in my repository. I think it would be a good addition to it.

    I also think the library should be decoubled from MSW implementation, so it removes work for you and usage will not add unused code. With this addition in mind we could even have parameters to modify handlers individually to differents tests scenarios.

    Thank you again and keep on the good work!

    opened by pikilon 0
  • Handlers are generated in the wrong order

    Handlers are generated in the wrong order

    Due to the inner workings of MSW, handlers must be defined in a certain order to avoid ambiguous paths. See more here. In short handlers with path parameters must be listed after handlers with static paths otherwise they will match to wrong path. A way to solve it would be to sort the handlers array by path. Thank you for the lib!

    opened by la55u 0
  • browser only support

    browser only support

    Hi @zoubingwu, first of all thanks for this, it's a great tool and saves a lot of time!

    There is one bit of the implementation that could simplify (in my opinion) the usage for a few people.

    When using Webpack in a client side app (eg a React app generated with https://create-react-app.dev/), there are issues in importing modules supposed to run in a node environment.

    Because of that, this bit causes a bit of issues:

    export const startWorker = () => {
      if (typeof window === "undefined") {
        const { setupServer } = require("msw/node");
        const server = setupServer(...handlers);
        server.listen();
      } else {
        const worker = setupWorker(...handlers);
        worker.start();
      }
    };
    

    do you think it would make sense to add a flag like --browser to change that piece of code to smaller when set? For example:

    export const startWorker = () => {
        const worker = setupWorker(...handlers);
        worker.start();
    };
    
    opened by teone 1
  • Change deprecated faker.name.findName() to faker.name.fullName()

    Change deprecated faker.name.findName() to faker.name.fullName()

    Hi there, thanks for this great package!

    I am running @faker-js/[email protected] in my project, and I'm seeing a warning in my console for each time findName is called:

    image

    So I followed their advice, and here's my console after this PR:

    image

    Thanks again.

    opened by chrisbarless 0
  • [BUG] Nested objects with `allOf` are being generated as null

    [BUG] Nested objects with `allOf` are being generated as null

    msw-auto-mock seems to have Problems with return values based on components/models with nested objects which have allOf instead of type. This is a standard open-api document and it's being generated by Swashbuckle See below the schema of the PaymentResultApiResponse and the result prop.

    Open-API Doc Example below

    "/v1/checkout/get-payment-status": {
          "post": {
            "tags": [
              "Checkout",
              "RequiresAuthentication",
              "RequiresKycTier-0"
            ],
            "operationId": "GetPaymentStatus",
            "requestBody": {
              "content": {
                "application/json": {
                  "schema": {
                    "allOf": [
                      {
                        "$ref": "#/components/schemas/GetPaymentStatusRequest"
                      }
                    ]
                  }
                }
              }
            },
            "responses": {
              "200": {
                "description": "Success",
                "content": {
                  "application/json": {
                    "schema": {
                      "$ref": "#/components/schemas/PaymentResultApiResponse"
                    }
                  }
                }
              },
              "429": {
                "description": "Too Many Requests"
              },
              "400": {
                "description": "Bad Request",
                "content": {
                  "application/json": {
                    "schema": {
                      "$ref": "#/components/schemas/ApiResponse"
                    }
                  }
                }
              }
            },
            "security": [
              { }
            ]
          }
        },
    
    // ...
      "components": {
        "schemas": {
            "PaymentResultApiResponse": {
                "required": [
                "isSuccessful"
                ],
                "type": "object",
                "properties": {
                "result": {
                    "allOf": [ <--- is not being generated
                    {
                        "$ref": "#/components/schemas/PaymentResult"
                    }
                    ],
                    "nullable": true
                },
                "timestamp": {
                    "type": "integer",
                    "format": "int64",
                    "readOnly": true
                },
                "isSuccessful": {
                    "type": "boolean"
                },
                "errorMessage": {
                    "type": "string",
                    "nullable": true
                },
                "errorCode": {
                    "type": "integer",
                    "format": "int32",
                    "nullable": true
                },
                "requestId": {
                    "type": "string",
                    "nullable": true
                }
                },
                "additionalProperties": false
            },
    

    Output:

     ctx.json({
              result: null,
              timestamp: faker.datatype.number(),
              isSuccessful: faker.datatype.boolean(),
              errorMessage: faker.lorem.slug(1),
              errorCode: faker.datatype.number(),
              requestId: faker.lorem.slug(1),
            }),
    
    opened by doubleppereira 4
  • Suggestions

    Suggestions

    hey, I really like this idea and I have thought of something that could improve it:

    I have a scenario where I also have to replicate functional business logic, so it would be nice if:

    • mocked responses were not inlined in each handlers,
    • mocked responses were exported so they could be mutate or used in @msw/data
    • handlers were generated with createHandler function that could take a mocked response as a param
    opened by asherccohen 2
Owner
build things to make life easier
null
LinkFree CLI is a command line tool that helps you to create your LinkFree profile through CLI.

LinkFree CLI LinkFree CLI is a command line tool that helps you to create your LinkFree profile through CLI. Demo Using the CLI (Commands) Note First

Pradumna Saraf 32 Dec 26, 2022
Node.js CLI tool to generate a set of favicons from a single input file.

This is a simple CLI tool to generate an optimized set of favicons from a single input file. Icons are optimized in terms of both size and quantity (n

null 6 Nov 11, 2022
DataENV is a cli tool that allows you to save data temporarily using your terminal.

DataEnv CLI Instllation npm install -g dataenv Usage Table of Contents LocalStorage npx dataenv save Parameters npx dataenv show Parameters npx dataen

PGamerX 2 Feb 5, 2022
Pretty diff to html javascript cli (diff2html-cli)

diff2html-cli Diff to Html generates pretty HTML diffs from unified and git diff output in your terminal Table of Contents Features Online Example Dis

Rodrigo Fernandes 404 Dec 19, 2022
CLI tool for running Yeoman generators

yo What's Yeoman? Yeoman helps you to kickstart new projects, prescribing best practices and tools to help you stay productive. To do so, we provide a

Yeoman 3.6k Dec 30, 2022
A simple CLI tool to create and manage xhelpers-api projects

A simple CLI tool to create and manage xhelpers-api projects

null 2 Feb 25, 2022
A CLI tool for project Pigeon.

Pigeon CLI [Incubating] A CLI tool for project Pigeon. Getting Start Download if you have node.js installed upon you machine, you can install pigeon-c

Pigeon 2 Feb 18, 2022
A CLI tool that allows you to ensure a database is live before closing the process

Wait for a database to be available prior to launching subsequent commands. ??⌛

Rida F'kih 3 Apr 16, 2022
Infinite Red's cutting edge React Native project boilerplate, along with a CLI, component/model generators, and more!

Ignite - the hottest React Native boilerplate Battle-tested React Native boilerplate The culmination of five years of constant React Native developmen

Infinite Red, Inc. 14.7k Dec 29, 2022
Test your internet connection speed and ping using speedtest.net from the CLI

speed-test Test your internet connection speed and ping using speedtest.net from the CLI Install Ensure you have Node.js version 8+ installed. Then ru

Sindre Sorhus 3.8k Jan 7, 2023
Distributed, realtime CLI for live Node apps.

Vantage = CLI + SSH + REPL for your live node app. In one line: require("vantage")().listen(4000); What just happened? That's voodoo magic: show me th

dc 3.5k Dec 30, 2022
download torrents with node from the CLI

torrent Download torrents from the command line usage torrent <magnet link OR path to .torrent file> Download a torrent from a magnet link to torre

Max Ogden 619 Dec 26, 2022
:white_square_button: WhatsApp chat from commandline/console/cli using GoogleChrome puppeteer

Whatspup Use Whatsapp from commandline/console/cli using GoogleChrome puppeteer! ?? Features ✅ Send and receive messages ✅ Read Receipts ✅ Switch betw

Sarfraz Ahmed 343 Dec 1, 2022
:notes: Control iTunes via CLI

itunes-remote Control iTunes via your terminal ?? Using JXA via osascript via Node.js. Requirements Node.js (v0.12.7 or greater) Mac OS X (Yosemite 10

Michael Kühnel 422 Nov 19, 2022
Add stdin support to any CLI app that accepts file input

tmpin Add stdin support to any CLI app that accepts file input It pipes stdin to a temp file and spawns the chosen app with the temp file path as the

Sindre Sorhus 121 Oct 3, 2022
A CLI for peer-to-peer file sharing using the Hypercore Protocol.

A CLI for peer-to-peer file sharing (and more) using the Hypercore Protocol.

Hypercore Protocol 207 Dec 30, 2022
Node.js Open CLI Framework. Built with 💜 by Heroku.

oclif: Node.JS Open CLI Framework ?? Description ?? Getting Started Tutorial ✨ Features ?? Requirements ?? CLI Types ?? Usage ?? Examples ?? Commands

oclif 8k Jan 4, 2023
Git commit CLI

commitme Based on this gist by @gustavopch Installation You can install this on your package using npm i -D commitme or run it once using npx commitme

Roz 7 Jun 6, 2021