Giter Site home page Giter Site logo

symbyte / openapi-json-mock-generator Goto Github PK

View Code? Open in Web Editor NEW

This project forked from 7nohe/openapi-mock-json-generator

0.0 0.0 0.0 267 KB

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

JavaScript 0.11% TypeScript 94.82% CSS 4.21% HTML 0.87%

openapi-json-mock-generator's Introduction

OpenAPI Mock Generator

Node.js library that generates mock API responses in JSON 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 openapi-json-mock-generator

Usage

$ openapi-json-mock-generator --help

Usage: openapi-json-mock-generator [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-mock-generator --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

openapi-json-mock-generator's People

Contributors

7nohe avatar masayuki0109 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.