Socket
Socket
Sign inDemoInstall

@7nohe/openapi-mock-json-generator

Package Overview
Dependencies
27
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    @7nohe/openapi-mock-json-generator

Generate mock API responses from OpenAPI specification file


Version published
Weekly downloads
80
decreased by-12.09%
Maintainers
1
Created
Weekly downloads
 

Readme

Source

OpenAPI Mock JSON Generator

Node.js library that generates mock API responses from an OpenAPI specification file.

Why

In some cases, using a mock server for testing is overdoing and simply preparing mock JSON data is enough.

You can save time and use practical responses by generating JSON data from the OpenAPI schema automatically.

Install

$ npm install -D @7nohe/openapi-mock-json-generator

Usage

$ openapi-json --help

Usage: openapi-json [options]

Generate mock data based on OpenAPI

Options:
  -V, --version               output the version number
  -i, --input <value>         OpenAPI specification, can be a path, url or string content (required)
  -o, --output <value>        Output directory (default: "mocks")
  --max-array-length <value>  Maximum length of array (default: "10")
  --locale <value>            Specifies the language of the data created by the mock (default: "en")
  -s, --seed <value>          Set a randomness seed (default: "1")
  -h, --help                  display help for command

Example Usage

An example can be found here.

Command

To generate JSON files, run the command below.

$ openapi-json --input ./petstore.yml

React Testing with MSW

React Components

Create a component to be tested.

// src/components/PetList.tsx
import { Pet } from "../../openapi/models/Pet";
import { PetService } from "../../openapi/services/PetService";
let data: Pet[] | undefined;

export const PetList = () => {
  if (data === undefined) {
    throw PetService.findPetsByStatus(["available"]).then((d) => (data = d));
  }

  return (
    <ul>
      {data.map((pet, index) => (
        <li data-testid="pet-list" key={index}>
          {pet.name}
        </li>
      ))}
    </ul>
  );
};

App.tsx should be like this.

// App.tsx
import { Suspense } from "react";
import "./App.css";
import { PetList } from "./components/PetList";


function App() {
  return (
    <div className="App">
      <h1>Pet List</h1>
      <Suspense fallback={<p>Loading...</p>}>
        <PetList/>
      </Suspense>
    </div>
  );
}

export default App;

Configuration

We'll need a setup script file for MSW.

There is no need to handwriting JSON responses. Just use the generated JSON file.

// tests/setup.ts
import { afterAll, afterEach, beforeAll } from "vitest";
import { setupServer } from "msw/node";
import { rest } from "msw";

// JSON file generated by OpenAPI Mock JSON Generator
import getPetFindByStatus from '../mocks/get-pet-findByStatus-200.json';

export const handlers = [
  rest.get("http://localhost:4010/pet/findByStatus", (req, res, ctx) => {
    return res(ctx.status(200), ctx.json(getPetFindByStatus));
  }),
];

const server = setupServer(...handlers);

// Start server before all tests
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));

//  Close server after all tests
afterAll(() => server.close());

// Reset handlers after each test `important for test isolation`
afterEach(() => server.resetHandlers());

Modify vite.config.ts for test.

// vite.config.ts
/// <reference types="vitest" />
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  test: {
    globals: true,
    environment: 'happy-dom',
    setupFiles: "./tests/setup.ts",
  },
  plugins: [react()]
})

Test
// tests/components/PetList.test.tsx
import { render, waitFor } from "@testing-library/react";
import { PetList } from "../../src/components/PetList";
import { describe, expect, it } from "vitest";

describe("PetList", () => {
  it("renders a list of pets", async () => {
    const { container, findAllByTestId } = render(<PetList />);
    await waitFor(() => findAllByTestId('pet-list'))
    expect(container.querySelectorAll("li").length).toEqual(4);
  });
});

License

MIT

Keywords

FAQs

Last updated on 05 Sep 2022

Did you know?

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

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc