English
Scene Mock
Scene Mock allows you to define multiple mock responses for the same URL and switch between them via scene configuration, without modifying mock files.
Basic Usage
Define mocks with different scenes for the same endpoint. Mocks without scene are universal and always active.
ts
import { defineMock } from 'vite-plugin-mock-dev-server'
/**
* Scene mocks.
*
* `activeScene: ['test']` is configured in `plugin-options.ts`, so `/api/scene`
* returns the `test` scene by default. The `X-Mock-Scene` request header overrides
* the configured scene for a single request.
*
* 场景 mock。
*
* `plugin-options.ts` 中配置了 `activeScene: ['test']`,因此 `/api/scene`
* 默认返回 `test` 场景;`X-Mock-Scene` 请求头可以按请求覆盖该配置。
*/
export default defineMock([
// Universal fallback: always active
// 通用兜底:始终激活
{
url: '/api/scene',
body: {
scene: 'universal',
activeScene: 'none matched',
},
},
{
url: '/api/scene',
scene: 'test',
body: {
scene: 'test',
data: { visible: true },
},
},
{
url: '/api/scene',
scene: 'demo',
body: {
scene: 'demo',
data: { curated: true },
},
},
{
url: '/api/scene',
scene: ['admin', 'demo'],
body: {
scene: 'admin or demo',
data: { privileged: true },
},
},
])Plugin Configuration
Configure the active scene in vite.config.ts:
ts
import { defineConfig } from 'vite'
import { mockDevServerPlugin } from 'vite-plugin-mock-dev-server'
export default defineConfig({
plugins: [
mockDevServerPlugin({
activeScene: 'test', // Activates the 'test' scene
}),
],
})When activeScene is set to 'test':
GET /api/scenewithout a matching scene → returns{ scene: 'default scene' }(universal, no scene)GET /api/scenewith scene'test'→ returns{ scene: 'test scene' }(scene match)
When activeScene is not configured (or empty):
GET /api/scene→ returns{ scene: 'default scene' }(only universal mock matches)
Per-Request Override
Use the X-Mock-Scene header to dynamically switch scenes per request:
ts
// Activate 'test' scene for this request
fetch('/api/scene', {
headers: { 'X-Mock-Scene': 'test' },
})
// Response: { scene: 'test scene' }The X-Mock-Scene header supports multiple comma-separated scenes:
ts
fetch('/api/scene', {
headers: { 'X-Mock-Scene': 'test,dev' },
})