Skip to content

测试

最好在支持 TypeScript 的测试运行器中进行 openapi-fetch 的测试,比如 Vitest 或 Jest。

模拟请求

要测试请求,可以使用 fetch 选项并提供任何 spy 函数,比如 vi.fn()(Vitest)或 jest.fn()(Jest)。

ts
import createClient from "openapi-fetch";
import { expect, test, vi } from "vitest";
import type { paths } from "./my-openapi-3-schema"; // 由openapi-typescript生成

test("my request", async () => {
  const mockFetch = vi.fn();
  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("/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-fetch";
import { afterEach, beforeAll, expect, test } from "vitest";
import type { paths } from "./my-openapi-3-schema"; // generated by openapi-typescript

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.
  server.listen({
    onUnhandledRequest: (request) => {
      throw new Error(
        `No request handler found for ${request.method} ${request.url}`
      );
    },
  });
});

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();
});

基于 MIT 许可发布