Testing
Testing openapi-typesafe-fetch is best done in a test runner that supports TypeScript, such as Vitest or Jest.
Mocking Requests
To test requests, the fetch option can be supplied with any spy function like vi.fn() (Vitest) or jest.fn() (Jest).
ts
import createClient from "openapi-typesafe-fetch";
import { expect, test, vi } from "vitest";
import type { paths } from "./my-openapi-3-schema"; // generated by openapi-typesafe
test("my request", async () => {
const mockFetch = vi.fn(async (_request: Request) => Response.json({}));
const client = createClient<paths>({
baseUrl: "https://my-site.com/api/v1",
fetch: mockFetch,
});
const reqBody = { name: "test" };
await client.PUT("/tag", { body: reqBody });
const req = mockFetch.mock.calls[0]![0];
expect(req.url).toBe("https://my-site.com/api/v1/tag");
expect(await req.json()).toEqual(reqBody);
});Mocking Responses
Mock Service Worker is highly recommended for mocking API responses in tests:
ts
import { http, HttpResponse } from "msw";
import { setupServer } from "msw/node";
import createClient from "openapi-typesafe-fetch";
import { afterEach, beforeAll, afterAll, expect, test } from "vitest";
import type { paths } from "./my-openapi-3-schema"; // generated by openapi-typesafe
const server = setupServer();
beforeAll(() => {
// NOTE: server.listen must be called before `createClient` is used to ensure
// the msw can inject its version of `fetch` to intercept the requests.
// Fail on a request no handler matches (msw 3; in msw 2 the option is `onUnhandledRequest`).
server.listen({ onUnhandledFrame: "error" });
});
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
test("my API call", async () => {
const rawData = { test: { data: "foo" } };
const BASE_URL = "https://my-site.com";
server.use(
http.get(`${BASE_URL}/api/v1/foo`, () =>
HttpResponse.json(rawData, { status: 200 })
)
);
const client = createClient<paths>({
baseUrl: BASE_URL,
});
const { data, error } = await client.GET("/api/v1/foo");
expect(data).toEqual(rawData);
expect(error).toBeUndefined();
});