Skip to content

Commit a676f49

Browse files
committed
docs: update en docs
1 parent 9c2d362 commit a676f49

4 files changed

Lines changed: 137 additions & 515 deletions

File tree

docs/en/guide/define-mock.md

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# defineMock(mockConfig)
22

3-
Mock configuration type helper function
3+
`defineMock` is a type helper function used for defining mock configurations, providing complete TypeScript type hints and code completion.
44

55
## Usage
66

@@ -13,7 +13,7 @@ export default defineMock({
1313
})
1414
```
1515

16-
Pass in an array:
16+
Supports passing an array to define multiple configurations:
1717

1818
```ts [*.mock.ts]
1919
import { defineMock } from 'vite-plugin-mock-dev-server'
@@ -30,8 +30,16 @@ export default defineMock([
3030
])
3131
```
3232

33-
## `mockConfig`
33+
## Parameters
3434

35-
`type: MockOptionsItem | MockOptionsItem[]`
35+
### mockConfig
3636

37-
See [mock-config](./mock-config)
37+
- **Type**: `MockHttpItem | MockHttpItem[] | MockWebsocketItem | MockWebsocketItem[]`
38+
- **Required**: Yes
39+
40+
Mock configuration object or configuration array.
41+
42+
## More Details
43+
44+
- View [Mock Configuration](./mock-config) for configuration item details
45+
- View [API Reference - defineMock](../api/define-mock) for complete type definitions and more examples

docs/en/guide/mock-config.md

Lines changed: 32 additions & 250 deletions
Original file line numberDiff line numberDiff line change
@@ -1,275 +1,57 @@
1-
# mockConfig
1+
# Mock Configuration
22

3-
`type: MockOptionsItem | MockOptionsItem[]`
3+
Mock configuration is used to define the mock response behavior of a single interface.
44

5-
::: code-group
5+
## Basic Structure
66

7-
```ts [*.mock.ts]
7+
```ts
88
import { defineMock } from 'vite-plugin-mock-dev-server'
99

1010
export default defineMock({
1111
url: '/api/test',
12-
body: {}
12+
method: 'GET',
13+
body: { message: 'Hello World' }
1314
})
1415
```
1516

16-
:::
17-
18-
**Type Definition:**
19-
20-
```ts
21-
interface RequestOptions {
22-
query: Record<string, string> // query string parse
23-
params: Record<string, string> // params parse
24-
headers: Record<string, string> // request headers
25-
body: any // request body
26-
getCookie: (name: string, option?: Cookies.GetOption) => string | void
27-
}
28-
```
29-
30-
**Description:**
31-
32-
::: warning
33-
If using json/json5 to write mock files, the `response` method is not supported, nor is the use of other field functions.
34-
:::
35-
36-
## url
37-
38-
- **Type**: `string`
39-
- **Required**
40-
41-
Request address.
42-
43-
Matching paths through the `path-to-regexp` library, supporting static URL matching and dynamic URL matching.
44-
45-
```ts
46-
export default defineMock([
47-
{
48-
url: '/api/post/list',
49-
},
50-
{
51-
url: '/api/post/:postId',
52-
}
53-
])
54-
```
55-
56-
## method
57-
58-
- **Type**: `Method | Method[]`
59-
- **Optional**
60-
- **Default**`['POST', 'GET']`
17+
## Configuration Overview
6118

62-
Supported request methods.
19+
| Configuration | Type | Required | Default | Description |
20+
|--------|------|------|--------|------|
21+
| [url](../api/mock-http-item#url) | `string` | Yes | - | Request path, supports dynamic parameters |
22+
| [method](../api/mock-http-item#method) | `Method \| Method[]` | No | `['GET','POST']` | Allowed HTTP methods |
23+
| [enabled](../api/mock-http-item#enabled) | `boolean` | No | `true` | Whether to enable |
24+
| [status](../api/mock-http-item#status) | `number` | No | `200` | Response status code |
25+
| [statusText](../api/mock-http-item#statustext) | `string` | No | `'OK'` | Response status text |
26+
| [headers](../api/mock-http-item#headers) | `Headers \| Function` | No | - | Response headers |
27+
| [body](../api/mock-http-item#body) | `ResponseBody \| Function` | No | `{}` | Response body |
28+
| [response](../api/mock-http-item#response) | `Function` | No | - | Custom response handling |
29+
| [delay](../api/mock-http-item#delay) | `number \| [number, number]` | No | `0` | Response delay |
30+
| [cookies](../api/mock-http-item#cookies) | `ResponseCookies \| Function` | No | - | Response Cookies |
31+
| [validator](../api/mock-http-item#validator) | `Validator \| Function` | No | - | Request validator |
32+
| [error](../api/mock-http-item#error) | `MockErrorConfig` | No | - | Error simulation configuration |
6333

64-
Only the matching request methods will return `mock data`, otherwise they will be ignored. Multiple request methods can be configured using an array.
34+
## Multiple Configurations
6535

66-
```ts
67-
type Method
68-
= | 'GET' | 'POST' | 'PUT' | 'DELETE'
69-
| 'PATCH' | 'HEAD' | 'TRACE' | 'OPTIONS'
70-
```
71-
72-
## enabled
73-
74-
- **Type**: `boolean`
75-
- **Optional**
76-
- **Default**: `true`
77-
78-
Whether to enable the current mock config.
36+
Multiple mock configurations can be exported in a single file:
7937

8038
```ts
81-
export default defineMock({
82-
url: 'api/test',
83-
enabled: false, // Disable this mock, api/test will not take effect
84-
})
85-
```
86-
87-
## status
88-
89-
- **Type**: `number`
90-
- **Optional**
91-
- **Default**`200`
92-
93-
Response status code.
94-
95-
## statusText
96-
97-
- **Type**: `string`
98-
- **Optional**
99-
- **Default**`'OK'`
100-
101-
Response status text.
102-
103-
## delay
104-
105-
- **Type**: `number | [number, number]`
106-
- **Optional**
107-
- **Unit**`ms`
108-
- **Default**`0`,not delay
109-
110-
Delayed Interface Response.
111-
112-
The response data is returned after a delay in responding to the interface. If an array is passed in, it represents the time range for delayed response.
113-
114-
## type
115-
116-
- **Type**: `'text' | 'json' | 'buffer' | string`
117-
- **Optional**
118-
- **Default**`'json'`
119-
120-
Set the `content-type` type. If it is a response of a file type, you can pass the file name as the value to `type`.
121-
122-
The actual `content-type` is determined internally by the plugin using `mime-types`.
123-
124-
## headers
125-
126-
- **Type**: `Record<string, string> | (request: RequestOptions) => Record<string, string>`
127-
- **Optional**
128-
- **Default**
129-
130-
The default value is determined based on the value of [type](#type):
131-
132-
| Type | Default |
133-
| -------- | -------------------------------------------------------- |
134-
| `text` | `{ 'Content-Type': 'text/plain' }` |
135-
| `json` | `{ 'Content-Type': 'application/json' }` |
136-
| `buffer` | `{ 'Content-Type': 'application/octet-stream' }` |
137-
| other | Determined based on the input value using `mime-types` |
138-
139-
Response headers
140-
141-
## cookies
142-
143-
- **Type**: `ResponseCookies | ResponseCookiesFn`
144-
- **Optional**
145-
- **Default**: `undefined`
146-
147-
Response cookies
148-
149-
```ts
150-
type CookieValue = string | [string, Cookies.SetOption]
151-
type ResponseCookies = Record<string, CookieValue>
152-
type ResponseCookiesFn = (
153-
request: RequestOptions,
154-
) => ResponseCookies | Promise<ResponseCookies>
155-
```
156-
157-
## body
158-
159-
- **Type**: `ResponseBody | ((request: RequestOptions) => ResponseBody | Promise<ResponseBody>)`
160-
- **Optional**
161-
- **Default**: `{}`
162-
163-
Response body data.
164-
165-
Define the content of the response body.
166-
167-
Support generating mock data body using `mockjs` or other third-party libraries.
168-
169-
``` ts
170-
type ResponseBody = string | number | array | object | Buffer | ReadableStream
171-
```
172-
173-
## response
174-
175-
- **Type**: `(req, res, next) => void | Promise<void>`
176-
- **Optional**
177-
- **Default**: `null`
178-
179-
If the mock requirements cannot be resolved through the `body` configuration, you can customize the configuration by exposing the HTTP server interface through the `response` configuration.
180-
The `req` parameter already includes the parsing of `query`, `body`, `params`, and `refererQuery`, as well as the `getCookie` method.
181-
The `res` parameter also includes the `setCookie` method, which you can use directly.
182-
183-
Don't forget to use `res.end()` to return the response body data, or use `next()` to skip the mock if necessary.
184-
185-
## validator
186-
187-
- **Type**: `Validator` | `ValidatorFn`
188-
189-
```ts
190-
interface Validator {
191-
header?: object
192-
body?: object
193-
query?: object
194-
params?: object
195-
refererQuery?: object
196-
}
197-
interface ValidatorFn {
198-
(request: RequestOptions): boolean
199-
}
200-
```
201-
202-
- **Optional**
203-
- **Default**`null`
204-
205-
Validator is used to determine whether to return mock data or not based on certain conditions.
206-
207-
This is useful in scenarios where an API needs to return different data based on different input parameters. By using a validator, you can divide the same URL into multiple mock configurations and determine which configuration to use based on the validator.
208-
209-
If the validator is an object, starting from version `v1.1.14`, it will check if the `headers/query/params/body/refererBody` configuration in the validator object is a subset of the corresponding request data. The comparison is deep, and if the attribute value is an array, all items in the array need to be present in the corresponding request data array.
210-
211-
If the validator is a function, the function will receive the relevant data of the request API as input and allow the user to perform custom validation. The function should return a boolean value.
212-
213-
Internally, the plugin parses the source page address that requests the mock API and extracts the `query` part of the URL, which is then parsed into `refererQuery`. This allows you to modify the page's `queryString` directly in the browser's address bar and determine the data returned by the mock API based on different `queryString` values.
39+
import { defineMock } from 'vite-plugin-mock-dev-server'
21440

215-
```ts
21641
export default defineMock([
21742
{
218-
url: 'api/list',
219-
validator: { query: { p: 1 } },
220-
body: {
221-
result: [{ title: 'p1' }],
222-
page: 1,
223-
}
43+
url: '/api/users',
44+
method: 'GET',
45+
body: []
22446
},
22547
{
226-
url: 'api/list',
227-
validator: { query: { p: 2 } },
228-
body: {
229-
result: [{ title: 'p2' }],
230-
page: 2,
231-
}
48+
url: '/api/users',
49+
method: 'POST',
50+
body: { id: 1 }
23251
}
23352
])
23453
```
23554

236-
## ws
237-
238-
- **Type**: `Boolean`
239-
- **Optional**
240-
- **Default**`false`
241-
242-
If you want to configure emulation of `Websocket`, you must explicitly specify the value of `ws` to be `true`
243-
244-
## setup
55+
## Detailed Documentation
24556

246-
- **Type**`(wss: WebSocketServer) => void`
247-
- **Optional**, If `ws` is `true`, this option is required
248-
249-
This option is only used for simulating `Websocket`.
250-
251-
```ts
252-
export default {
253-
ws: true,
254-
setup(wss, { onCleanup }) {
255-
// `wss` is an instance of `WebSocketServer` on the server side,
256-
// where each request address corresponds to a `wss`.
257-
// However, multiple clients are allowed to simultaneously request
258-
// this address to establish a WebSocket connection.
259-
// In the `connection` event listener, the callback parameter `ws`
260-
// represents the `ws` connection of one of the clients.
261-
wss.on('connection', (ws, res) => {
262-
ws.on('message', (raw) => {
263-
console.log(raw)
264-
})
265-
const timer = setInterval(() => {
266-
ws.send('data')
267-
}, 2000)
268-
// Clear automatic tasks or terminate other method executions in this function
269-
// However, there is no need to delete the event listeners for wss and ws inside this function
270-
// The plugin will automatically handle this during hot updates to avoid duplicate event listeners
271-
onCleanup(() => clearInterval(timer))
272-
})
273-
}
274-
}
275-
```
57+
View [API Reference - MockHttpItem](../api/mock-http-item) for complete configuration item descriptions and examples.

0 commit comments

Comments
 (0)