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.
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.
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.
import { afterAll, afterEach, beforeAll } from "vitest";
import { setupServer } from "msw/node";
import { rest } from "msw";
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);
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
afterAll(() => server.close());
afterEach(() => server.resetHandlers());
Modify vite.config.ts
for test.
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
test: {
globals: true,
environment: 'happy-dom',
setupFiles: "./tests/setup.ts",
},
plugins: [react()]
})
Test
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