|
1 | 1 | ---
|
2 |
| -title: Testing |
| 2 | +title: 测试 |
3 | 3 | ---
|
4 | 4 |
|
5 |
| -# Testing |
| 5 | +# 测试 |
6 | 6 |
|
7 |
| -::: warning |
| 7 | +最好在支持 TypeScript 的测试运行器中进行 openapi-fetch 的测试,比如 [Vitest](https://vitest.dev/) 或 Jest。 |
8 | 8 |
|
9 |
| -This article is a stub. Please help [expand it](https://github.com/drwpow/openapi-typescript/tree/main/docs/zh/)! |
| 9 | +## 模拟请求 |
10 | 10 |
|
11 |
| -::: |
| 11 | +要测试请求,可以使用 `fetch` 选项并提供任何 spy 函数,比如 `vi.fn()`(Vitest)或 `jest.fn()`(Jest)。 |
| 12 | + |
| 13 | +```ts |
| 14 | +import createClient from "openapi-fetch"; |
| 15 | +import { expect, test, vi } from "vitest"; |
| 16 | +import type { paths } from "./api/v1"; |
| 17 | + |
| 18 | +test("my request", async () => { |
| 19 | + const mockFetch = vi.fn(); |
| 20 | + const client = createClient<paths>({ |
| 21 | + baseUrl: "https://my-site.com/api/v1/", |
| 22 | + fetch: mockFetch, |
| 23 | + }); |
| 24 | + |
| 25 | + const reqBody = { name: "test" }; |
| 26 | + await client.PUT("/tag", { body: reqBody }); |
| 27 | + |
| 28 | + const req = mockFetch.mock.calls[0][0]; |
| 29 | + expect(req.url).toBe("/tag"); |
| 30 | + expect(await req.json()).toEqual(reqBody); |
| 31 | +}); |
| 32 | +``` |
| 33 | + |
| 34 | +## 模拟响应 |
| 35 | + |
| 36 | +任何能够模拟原生 `fetch` API 的库都可以工作,比如 [vitest-fetch-mock](https://github.com/IanVS/vitest-fetch-mock): |
| 37 | + |
| 38 | +```ts |
| 39 | +import createClient from "openapi-fetch"; |
| 40 | +import { afterEach, beforeAll, expect, test, vi } from "vitest"; |
| 41 | +import type { paths } from "./api/v1"; |
| 42 | + |
| 43 | +const fetchMocker = createFetchMock(vi); |
| 44 | + |
| 45 | +beforeAll(() => { |
| 46 | + fetchMocker.enableMocks(); |
| 47 | +}); |
| 48 | +afterEach(() => { |
| 49 | + fetchMocker.resetMocks(); |
| 50 | +}); |
| 51 | + |
| 52 | +test("my API call", async () => { |
| 53 | + const rawData = { test: { data: "foo" } }; |
| 54 | + mockFetchOnce({ |
| 55 | + status: 200, |
| 56 | + body: JSON.stringify(rawData), |
| 57 | + }); |
| 58 | + const client = createClient<paths>({ |
| 59 | + baseUrl: "https://my-site.com/api/v1/", |
| 60 | + }); |
| 61 | + |
| 62 | + const { data, error } = await client.GET("/foo"); |
| 63 | + |
| 64 | + expect(data).toEqual(rawData); |
| 65 | + expect(error).toBeUndefined(); |
| 66 | +}); |
| 67 | +``` |
0 commit comments