Node.js library that generates mock API responses from an OpenAPI specification file.
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.
$ npm install -D @7nohe/openapi-mock-json-generator
$ 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
An example can be found here.
To generate JSON files, run the command below.
$ openapi-json --input ./petstore.yml
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;
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()]
})
// 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);
});
});
MIT