vite-plugin-mock

repository·main·Indexed 20 days ago

https://github.com/vbenjs/vite-plugin-mock

A Vite plugin providing local and production mocking capabilities. It utilizes Connect middleware for local development to ensure Chrome DevTools visibility and MockJS for production/online environments. The plugin supports automatic mock file watching, custom response handlers via MockMethod, and environment-specific configurations using defineMockModule and createProdMockServer.

Tokens
4.7K
Snippets
15
Records
19
Agent score
70%

What's inside vite-plugin-mock

  1. Setup mock server for production environments

    main

    In production, vite-plugin-mock uses mockjs instead of Connect middleware. This means you cannot access headers or use certain restful URL parameter formats.

    To use mocks in production, you must create a mockProdServer.ts file and call createProdMockServer with your mock modules.

    Important Limitations:

    • No Node Modules: You cannot use Node.js modules inside your mock.ts files, otherwise production will fail.
    • Testing Only: Only use production mocks for specific testing environments. Do not enable them in actual production environments as they may interfere with real Ajax requests (e.g., file uploads/downloads).
    // mockProdServer.ts
    import { createProdMockServer } from 'vite-plugin-mock/client'
    import testModule from '../mock/test'
    
    export function setupProdMockServer() {
      createProdMockServer([...testModule])
    }
  2. Install vite-plugin-mock and mockjs

    main

    To use vite-plugin-mock in both development and production environments, you must install both the plugin and mockjs.

    Requirements:

    • Node version: >=12.0.0
    • Vite version: >=2.0.0

    Install using your preferred package manager:

    # Install mockjs
    yarn add mockjs
    # or
    npm i mockjs -S
    # or
    pnpm add mockjs
    
    # Install vite-plugin-mock
    yarn add vite-plugin-mock -D
    # or
    npm i vite-plugin-mock -D
    # or
    pnpm add vite-plugin-mock -D
  3. Setup production mocks with createProdMockServer

    main

    For production environments (or environments simulating production), use createProdMockServer from vite-plugin-mock/client. This typically involves creating a setup file that imports your mock modules and passes them to the server creator.

    Note: Do not use Node.js modules inside your mock .ts files, as this will cause the production environment to fail.

    // mockProdServer.ts
    import { createProdMockServer } from 'vite-plugin-mock/client'
    import testModule from '../mock/test'
    
    export function setupProdMockServer() {
      createProdMockServer([...testModule])
    }
  4. Configure viteMockServe in vite.config.ts

    main

    To enable mocking in your development environment, add viteMockServe to your Vite plugins array in vite.config.ts. By default, it looks for mock files in a folder named mock and is enabled by default.

    import { UserConfigExport, ConfigEnv } from 'vite'
    import { viteMockServe } from 'vite-plugin-mock'
    import vue from '@vitejs/plugin-vue'
    
    export default ({ command }: ConfigEnv): UserConfigExport => {
      return {
        plugins: [
          vue(),
          viteMockServe({
            // default
            mockPath: 'mock',
            enable: true,
          }),
        ],
      }
    }
  5. Configure vite-plugin-mock in vite.config.ts

    main

    Add viteMockServe to your Vite plugins array. In development, it uses a Connect middleware which allows you to inspect network requests in the Chrome DevTools console.

    import { UserConfigExport, ConfigEnv } from 'vite'
    import { viteMockServe } from 'vite-plugin-mock'
    import vue from '@vitejs/plugin-vue'
    
    export default ({ command }: ConfigEnv): UserConfigExport => {
      return {
        plugins: [
          vue(),
          viteMockServe({
            mockPath: 'mock',
            enable: true,
          }),
        ],
      }
    }
  6. Configure viteMockServe options

    main

    The viteMockServe function accepts the following configuration options:

    OptionTypeDefaultDescription
    mockPathstring'mock'The folder where mock .ts files are stored. If configPath is set, this is ignored.
    ignoreRegExp or (fileName: string) => booleanundefinedIgnore files in the specified format when automatically reading mock files.
    watchFilesbooleantrueWhether to monitor changes in mock .ts files and synchronize results in real time.
    enablebooleantrueWhether to enable the mock function.
    ignoreFilesstring[]undefinedList of files to ignore.
    configPathstring'vite.mock.config.ts'The data entry the mock reads. If this file exists in the project root, it is used first.
    loggerbooleantrueWhether to display request logs in the console.
  7. Configure mock file watching

    main

    The plugin includes a built-in watcher that automatically reloads mock data when files change.

    Key behaviors:

    • Activation: Watching is enabled by default via the watchFiles: true option.
    • Files Watched: It watches the configPath file and the mockPath directory.
    • Disabling: You can disable the watcher by setting watchFiles: false in your options, or by setting the environment variable VITE_DISABLED_WATCH_MOCK=true.
    • Implementation: It uses chokidar to monitor changes and clears the require cache to ensure fresh modules are loaded.
  8. How the mock server and request middleware work

    main

    The vite-plugin-mock operates by creating a mock server that intercepts incoming HTTP requests.

    1. Mock Data Loading: The server loads mock definitions from either a specific configuration file (defined by configPath) or by scanning a directory (defined by mockPath) for .ts, .mjs, or .js files.
    2. Request Interception: The requestMiddleware function is used as a middleware in the development server. When a request arrives, the middleware checks the url and method against the loaded mockData.
    3. Response Generation: If a match is found, the server can return a static response, a dynamic response function, or a rawResponse function. It also supports a timeout to simulate network latency.
    4. Mocking Engine: The final response is processed through mockjs to generate randomized data based on the provided templates.
  9. Define MockMethod for API mocks

    main

    A mock definition is an array of MockMethod objects. Each object defines how to handle a specific request.

    PropertyTypeDescription
    urlstringThe request URL.
    methodMethodTypeThe HTTP method (e.g., 'get', 'post').
    timeoutnumberRequest delay in milliseconds.
    statusCodenumberThe HTTP status code to return (default: 200).
    responseFunction or anyThe JSON response data. If a function, it receives an object containing query, body, headers, etc.
    rawResponse(req: IncomingMessage, res: ServerResponse) => voidA function for non-JSON responses, allowing direct manipulation of the Node.js request/response objects.
    import { MockMethod, MockConfig } from 'vite-plugin-mock'
    
    export default [
      {
        url: '/api/get',
        method: 'get',
        response: ({ query }) => {
          return {
            code: 0,
            data: { name: 'vben' },
          }
        },
      },
      {
        url: '/api/post',
        method: 'post',
        timeout: 2000,
        response: { code: 0, data: { name: 'vben' } },
      },
      {
        url: '/api/text',
        method: 'post',
        rawResponse: async (req, res) => {
          // Handle raw stream/buffer logic here
        },
      },
    ] as MockMethod[]
  10. Define mock data using MockMethod

    main

    Mock files should export an array of MockMethod objects. Each object defines a route and its corresponding response behavior.

    MockMethod Properties:

    • url: The request URL (string).
    • method: The HTTP method (e.g., 'get', 'post').
    • timeout: Timeout setting (number).
    • statusCode: HTTP status code (number).
    • response: The response data. Can be a static object/value or a function: (opt) => any. The function receives an object containing query, body, headers, and [key: string].
    • rawResponse: A function for non-JSON responses (e.g., text/plain). It receives (req: IncomingMessage, res: ServerResponse).
    import { MockMethod, MockConfig } from 'vite-plugin-mock'
    
    export default [
      {
        url: '/api/get',
        method: 'get',
        response: ({ query }) => {
          return {
            code: 0,
            data: { name: 'vben' },
          }
        },
      },
      {
        url: '/api/post',
        method: 'post',
        timeout: 2000,
        response: { code: 0, data: { name: 'vben' } },
      },
      {
        url: '/api/text',
        method: 'post',
        rawResponse: async (req, res) => {
          let reqbody = ''
          await new Promise((resolve) => {
            req.on('data', (chunk) => { reqbody += chunk })
            req.on('end', () => resolve(undefined))
          })
          res.setHeader('Content-Type', 'text/plain')
          res.statusCode = 200
          res.end(`hello, ${reqbody}`)
        },
      },
    ] as MockMethod[]
  11. Configure vite-plugin-mock via ViteMockOptions

    main

    When initializing the plugin in your vite.config.ts, you can pass a ViteMockOptions object to control its behavior. Key options include:

    • mockPath: The directory where your mock files are located.
    • configPath: The path to your mock configuration file.
    • ignore: A RegExp or a function (fileName: string) => boolean to exclude specific files from being processed.
    • watchFiles: Boolean to enable/disable watching for file changes.
    • enable: Boolean to enable/disable the plugin.
    • logger: Boolean to enable/disable logging.
    • cors: Boolean to enable/disable CORS support.
    // Example configuration object
    const options: ViteMockOptions = {
      mockPath: 'src/mock',
      enable: true,
      watchFiles: true,
      ignore: /\.test\.ts$/
    };
  12. Define a mock endpoint with MockMethod

    main

    The MockMethod interface defines how a single mock endpoint is structured. You can specify the URL, HTTP method, response delay, and status code.

    There are two ways to define a response:

    1. response: A function or a static value. If it is a function, it can access req, res, and parseJson() via the this context (of type RespThisType). The function receives an object containing url, body, query, and headers.
    2. rawResponse: A function that provides direct access to the Node.js IncomingMessage (req) and ServerResponse (res) objects for low-level control.
    import { MockMethod } from 'vite-plugin-mock';
    
    const mock: MockMethod = {
      url: '/api/user',
      method: 'post',
      timeout: 1000,
      statusCode: 200,
      // Using the response function with 'this' context
      response: function({ body, query }) {
        return { 
          code: 0, 
          message: 'success', 
          data: body 
        };
      }
    };
    
    // Or using rawResponse for direct Node.js response control
    const rawMock: MockMethod = {
      url: '/api/raw',
      rawResponse: (req, res) => {
        res.setHeader('Content-Type', 'text/plain');
        res.end('Raw response content');
      }
    };