npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@7nohe/openapi-mock-json-generator

v0.1.1

Published

Generate mock API responses from OpenAPI specification file

Downloads

296

Readme

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