Skip to content

以下提供 3 套项目专属 Jest 配置模板,分别适配「Vue 2 + JS」「Vue 3 + TS」「Vue 2 + Element UI + 真实接口测试」主流场景,可直接复制使用并微调细节:

模板 1:Vue 2 + JavaScript + Vue Test Utils v1

适合 Vue 2 纯 JS 项目,适配 Vue Test Utils v1,包含基础模块解析、样式忽略、覆盖率配置。

javascript
// jest.config.js
module.exports = {
  // 基础配置
  testMatch: [
    "**/__tests__/**/*.spec.js", // __tests__ 目录下的 .spec.js 文件
    "**/?(*.)+(spec|test).js", // 根目录或 src 下的 .test.js/.spec.js 文件
  ],
  testEnvironment: "jsdom", // 模拟浏览器环境
  testTimeout: 10000, // 单个用例超时 10 秒(适配异步/接口测试)
  rootDir: process.cwd(), // 项目根目录
  roots: ["<rootDir>/src", "<rootDir>/tests"], // 限制搜索范围提升效率

  // 模块解析(适配 Vue 2 目录结构)
  moduleFileExtensions: ["js", "vue", "json"], // 识别的文件后缀
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1", // 映射 @ 到 src 目录(与 Vue CLI 一致)
    "^.+\\.(css|scss|less|styl)$": "jest-transform-stub", // 忽略样式文件
    "^.+\\.(png|jpg|jpeg|gif|svg|ico)$": "jest-transform-stub", // 忽略图片资源
  },

  // 转换器配置(编译 JS/Vue)
  transform: {
    "^.+\\.js$": "babel-jest", // 编译 ES6+ 语法
    "^.+\\.vue$": "vue-jest@3", // Vue 2 适配 vue-jest@3(关键版本!)
  },
  transformIgnorePatterns: [
    "/node_modules/(?!vue|element-ui|@vue/shared)/", // 第三方模块需转换的例外(如 Element UI)
  ],

  // 测试初始化脚本
  setupFiles: ["<rootDir>/tests/setup.global.js"], // 同步初始化(如全局变量、环境配置)
  setupFilesAfterEnv: ["<rootDir>/tests/setup.jest.js"], // 异步初始化(如 Vue Test Utils 配置)

  // 覆盖率配置
  collectCoverageFrom: [
    "src/**/*.{js,vue}", // 统计 src 下所有 JS/Vue 文件
    "!src/main.js", // 排除入口文件
    "!src/router/index.js", // 排除路由配置
    "!src/store/index.js", // 排除 Store 入口
    "!**/node_modules/**",
    "!**/vendor/**",
  ],
  coverageReporters: ["text", "html", "lcov"], // 终端+HTML+LCOV 报告
  coverageDirectory: "<rootDir>/tests/coverage", // 覆盖率报告输出目录
  coverageThreshold: {
    // 覆盖率阈值(按需调整)
    global: {
      branches: 60,
      functions: 70,
      lines: 80,
      statements: 80,
    },
  },

  // Mock 配置(避免用例间污染)
  clearMocks: true, // 每个用例后清除 mock 调用记录
  restoreMocks: true, // 恢复 spyOn 监视的方法
  globals: {
    "vue-jest": {
      compilerOptions: {
        preserveWhitespace: false, // 移除 Vue 模板空白字符(与项目配置一致)
      },
    },
  },
};

配套初始化脚本示例:

  1. tests/setup.global.js(同步初始化):
javascript
// 全局引入 Vue(避免每个测试文件重复导入)
import Vue from "vue";
window.Vue = Vue;

// 模拟全局工具函数(如 $message)
Vue.prototype.$message = {
  success: jest.fn(),
  error: jest.fn(),
};
  1. tests/setup.jest.js(异步初始化):
javascript
// 引入 Vue Test Utils 全局方法
import { config } from "@vue/test-utils";

// 配置 Vue Test Utils(如全局 stub 组件)
config.stubs["ElButton"] = true; // 全局 stub Element UI 按钮组件

模板 2:Vue 3 + TypeScript + Vue Test Utils v2

适合 Vue 3 + TS 项目,适配 Vue Test Utils v2 和 ts-jest,支持 TS 类型解析、Vue 3 组件模型。

javascript
// jest.config.js
module.exports = {
  // 基础配置
  testMatch: ["**/__tests__/**/*.spec.{js,ts}", "**/?(*.)+(spec|test).{js,ts}"],
  testEnvironment: "jsdom",
  testTimeout: 10000,
  rootDir: process.cwd(),
  roots: ["<rootDir>/src", "<rootDir>/tests"],

  // 预设(简化 TS 配置)
  preset: "ts-jest",

  // 模块解析
  moduleFileExtensions: ["ts", "tsx", "js", "vue", "json"],
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1",
    "^.+\\.(css|scss|less)$": "jest-transform-stub",
    "^.+\\.(png|jpg|svg)$": "jest-transform-stub",
  },

  // 转换器配置
  transform: {
    "^.+\\.vue$": "@vue/vue3-jest", // Vue 3 专用 vue-jest
    "^.+\\.tsx?$": [
      "ts-jest",
      {
        tsconfig: "<rootDir>/tsconfig.test.json", // 测试专用 TS 配置
        isolatedModules: true, // 提升编译速度
      },
    ],
    "^.+\\.js$": "babel-jest",
  },
  transformIgnorePatterns: ["/node_modules/(?!vue|@vue/*|vue-router)/"],

  // 初始化脚本
  setupFiles: ["<rootDir>/tests/setup.global.ts"],
  setupFilesAfterEnv: ["<rootDir>/tests/setup.jest.ts"],

  // 覆盖率配置
  collectCoverageFrom: [
    "src/**/*.{ts,vue,js}",
    "!src/main.ts",
    "!src/router/index.ts",
    "!src/store/index.ts",
    "!**/node_modules/**",
  ],
  coverageReporters: ["text", "html", "lcov"],
  coverageDirectory: "<rootDir>/tests/coverage",
  coverageThreshold: {
    global: {
      branches: 60,
      functions: 70,
      lines: 80,
      statements: 80,
    },
  },

  // Mock 与全局配置
  clearMocks: true,
  restoreMocks: true,
  globals: {
    "ts-jest": {
      tsconfig: "<rootDir>/tsconfig.test.json",
    },
    "@vue/vue3-jest": {
      compilerOptions: {
        isCustomElement: (tag) => tag.startsWith("el-"), // 识别 Element Plus 自定义标签
      },
    },
  },
};

配套 tsconfig.test.json

json
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "jsx": "preserve",
    "module": "CommonJS",
    "target": "ES2018",
    "esModuleInterop": true,
    "skipLibCheck": true
  },
  "include": ["tests/**/*", "src/**/*"],
  "exclude": ["node_modules"]
}

模板 3:Vue 2 + Element UI + 真实接口测试

适合需要调用真实接口、依赖 Element UI 的 Vue 2 项目,优化接口超时、避免 mock 污染。

javascript
// jest.config.js
module.exports = {
  // 基础配置
  testMatch: ["**/__tests__/**/*.spec.js", "**/?(*.)+(spec|test).js"],
  testEnvironment: "jsdom",
  testTimeout: 20000, // 接口测试超时 20 秒(关键!)
  rootDir: process.cwd(),
  roots: ["<rootDir>/src", "<rootDir>/tests"],

  // 模块解析(适配 Element UI)
  moduleFileExtensions: ["js", "vue", "json"],
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1",
    "^.+\\.(css|scss|less)$": "jest-transform-stub",
    "^.+\\.(png|jpg|svg|woff|ttf)$": "jest-transform-stub",
  },

  // 转换器配置
  transform: {
    "^.+\\.js$": "babel-jest",
    "^.+\\.vue$": "vue-jest@3",
    // 处理 Element UI 部分 ES6+ 语法
    "^.+\\.jsx?$": "babel-jest",
  },
  transformIgnorePatterns: [
    "/node_modules/(?!vue|element-ui|axios)/", // 允许转换 axios/Element UI
  ],

  // 初始化脚本(配置 Element UI 全局注册)
  setupFiles: ["<rootDir>/tests/setup.global.js"],
  setupFilesAfterEnv: ["<rootDir>/tests/setup.jest.js"],

  // 覆盖率配置(接口测试可降低阈值)
  collectCoverageFrom: [
    "src/**/*.{js,vue}",
    "!src/api/**", // 排除真实接口文件(无需统计覆盖率)
    "!src/main.js",
    "!src/utils/request.js", // 排除请求封装
    "!**/node_modules/**",
  ],
  coverageReporters: ["text", "html"],
  coverageDirectory: "<rootDir>/tests/coverage",
  coverageThreshold: {
    global: {
      branches: 50,
      functions: 60,
      lines: 70,
      statements: 70,
    },
  },

  // Mock 配置(关键:关闭自动 mock,手动控制)
  automock: false, // 禁用自动 mock(避免接口被 mock)
  clearMocks: true,
  restoreMocks: true,
  unmockedModulePathPatterns: [
    "axios", // 不 mock axios(真实接口调用)
    "element-ui", // 不 mock Element UI(真实组件渲染)
    "@/api", // 不 mock 接口文件
  ],

  // 全局配置
  globals: {
    "vue-jest": {
      compilerOptions: {
        preserveWhitespace: false,
      },
    },
    // 接口测试环境变量
    TEST_API_BASE_URL: "https://test-api.your-project.com", // 测试环境接口地址
  },
};

配套 setup.global.js(注册 Element UI):

javascript
import Vue from "vue";
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css"; // 引入 Element UI 样式

// 全局注册 Element UI
Vue.use(ElementUI);

// 配置全局接口地址
process.env.VUE_APP_API_BASE_URL = global.TEST_API_BASE_URL;

模板使用说明:

  1. 复制对应模板:根据项目技术栈选择模板,粘贴到项目根目录 jest.config.js
  2. 微调关键配置
    • testTimeout:接口测试/复杂组件测试需增大(如 20000)。
    • moduleNameMapper:根据项目实际别名调整(如 ^@views/(.*)$ 映射到 src/views/$1)。
    • coverageThreshold:根据团队代码质量要求调整覆盖率阈值。
  3. 添加初始化脚本:按模板中的路径创建 setup.global.js/setup.jest.js,注册全局组件/工具。

要不要我帮你根据你的具体项目信息(Vue 版本、是否用 TS、是否需要接口测试)进一步定制化配置?

Released under the MIT License.