🛠️ 零基础接入自动化测试 —— 实操手册(Vue3 + Vite / React + Vite 通用版)

6 阅读6分钟

专为前端初学者设计 | 不懂测试也能上手 | 手把手带你从 npm create vue@latest 到跑通第一个自动化测试
✅ 支持 Vue3 + Vite 和 React + Vite 项目
✅ 包含完整命令、代码示例、常见问题解决


📌 适用人群

  • 刚学会 Vue/React 的新手
  • 想给自己的小项目加测试但不知从何开始
  • 完全没接触过 Jest、Testing Library 等工具

目录

  1. 🎯 我们要做什么?
  2. 🔧 环境准备
  3. 📦 创建项目(Vue 或 React)
  4. 🧪 第一步:安装测试工具
  5. 📝 第二步:写你的第一个测试用例
  6. ▶️ 第三步:运行测试
  7. 🖼️ 第四步:快照测试(Snapshot Test)
  8. 🌐 第五步:端到端测试(E2E)入门
  9. 🔄 第六步:集成到开发流程(保存自动测)
  10. 🚀 第七步:提交时自动检查(Git Hook)
  11. 💡 常见问题与解决方案
  12. 📌 总结 checklist

🎯 我们要做什么?

我们将完成以下目标:

✅ 创建一个简单的前端项目(Vue 或 React)
✅ 添加单元测试支持
✅ 写一个测试:验证页面是否显示“Hello World”
✅ 运行测试并看到绿色 ✅
✅ 设置保存文件时自动运行测试
✅ 提交代码前自动检测测试是否通过

最终效果:

PASS  src/components/__tests__/HelloWorld.test.js
  ✓ should render hello world (23ms)

🔧 环境准备

请确保你已安装:

工具版本要求下载地址
Node.jsv16+(推荐 v18 或 v20)nodejs.org
npm自带npm -v 查看版本
Git可选(用于最后一步)git-scm.com

💡 推荐使用 Node.js LTS 版本

在终端中检查:

node -v   # 应输出 v18.x 或 v20.x
npm -v    # 应输出 8.x 或以上

📦 创建项目(Vue 或 React)

你可以选择其中一种框架,我们分别演示。


方式一:Vue3 + Vite 项目

npm create vue@latest my-vue-app

按提示选择:

✔ Project name: … my-vue-app
✔ Add TypeScript? … NoAdd JSX Support? … NoAdd Vue Router for Single Page Application development? … NoAdd Pinia for state management? … NoAdd Vitest for Unit testing? … Yes ✅
✔ Add an End-to-end Testing Solution? … NoAdd ESLint for code quality? … Yes

进入项目:

cd my-vue-app
npm install

方式二:React + Vite 项目

npm create vite@latest my-react-app --template react
cd my-react-app
npm install

然后手动添加测试工具(下一步会教)。


🧪 第一步:安装测试工具

根据你的项目类型执行对应命令。


如果是 Vue 项目(已选 Vitest)

你已经装好了!🎉
Vitest 是现代前端推荐的测试框架,速度极快。

只需再安装 DOM 测试库:

npm install -D @testing-library/vue jsdom

如果是 React 项目

我们需要安装 Jest + Testing Library

npm install -D jest @testing-library/react @testing-library/jest-dom babel-jest identity-obj-proxy

创建配置文件:

1. jest.config.js

// jest.config.js
module.exports = {
  testEnvironment: 'jsdom',
  setupFilesAfterEnv: ['<rootDir>/src/setupTests.js'],
  transform: {
    '^.+\.(js|jsx)$': 'babel-jest'
  },
  moduleNameMapper: {
    '\.(css|less|scss|sass)$': 'identity-obj-proxy'
  }
}

2. src/setupTests.js(创建该文件)

// src/setupTests.js
import '@testing-library/jest-dom';

3. 在 package.json 中添加脚本

"scripts": {
  "test": "jest",
  "test:watch": "jest --watch"
}

📝 第二步:写你的第一个测试用例

现在我们来测试一个最简单的组件。


示例:测试 HelloWorld.vueHelloWorld.jsx

文件路径:src/components/HelloWorld.vue

<template>
  <div class="hello">
    <h1>Hello World</h1>
    <p>Welcome to my app!</p>
  </div>
</template>
<script>
export default {
  name: 'HelloWorld'
}
</script>

或 React 版本:src/components/HelloWorld.jsx

export default function HelloWorld() {
  return (
    <div className="hello">
      <h1>Hello World</h1>
      <p>Welcome to my app!</p>
    </div>
  );
}

添加测试文件

Vue 项目:src/components/__tests__/HelloWorld.test.js

// src/components/__tests__/HelloWorld.test.js
import { render } from '@testing-library/vue'
import HelloWorld from '../HelloWorld.vue'

test('should render hello world', () => {
  const { getByText } = render(HelloWorld)

  expect(getByText(/Hello World/i)).toBeInTheDocument()
  expect(getByText(/Welcome to my app/i)).toBeInTheDocument()
})

React 项目:src/components/__tests__/HelloWorld.test.js

// src/components/__tests__/HelloWorld.test.js
import { render, screen } from '@testing-library/react'
import '@testing-library/jest-dom'
import HelloWorld from '../HelloWorld'

test('should render hello world', () => {
  render(<HelloWorld />)

  expect(screen.getByText(/Hello World/i)).toBeInTheDocument()
  expect(screen.getByText(/Welcome to my app/i)).toBeInTheDocument()
})

✅ 注意:

  • getByText 会查找包含指定文本的元素
  • /Hello World/i 是正则表达式,表示忽略大小写
  • toBeInTheDocument() 是来自 @testing-library/jest-dom 的断言

▶️ 第三步:运行测试

启动测试

npm test

首次运行可能会慢一点,之后会很快。

✅ 成功输出应类似:

PASS  src/components/__tests__/HelloWorld.test.js
✓ should render hello world (18ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total

🎉 恭喜!你已经成功运行了人生第一个自动化测试!


🖼️ 第四步:快照测试(Snapshot Test)

快照测试可以“记住”组件长什么样,防止意外修改。

添加快照测试

在同一个测试文件中追加:

// Vue 和 React 通用
test('matches snapshot', () => {
  const { asFragment } = render(HelloWorld)
  expect(asFragment()).toMatchSnapshot()
})

第一次运行时会生成一个 __snapshots__ 文件夹,内容如下:

// __snapshots__/HelloWorld.test.js.snap
exports[`HelloWorld matches snapshot 1`] = `
<DocumentFragment>
  <div
    class="hello"
  >
    <h1>
      Hello World
    </h1>
    <p>
      Welcome to my app!
    </p>
  </div>
</DocumentFragment>
`;

下次如果组件结构变了,测试就会失败,提醒你确认是否为预期变更。


🌐 第五步:端到端测试(E2E)入门

我们用 Playwright(微软出品,超简单好用)

安装 Playwright

npx playwright install-deps
npm install -D @playwright/test

初始化配置

npx playwright init

按提示选择:

  • 项目类型:Empty
  • 浏览器:Chromium
  • 是否运行示例:Yes

会生成 playwright.config.jstests/example.spec.js

写一个 E2E 测试

启动本地服务(先构建并预览):

npm run dev
# 记住端口,通常是 http://localhost:5173

修改 playwright.config.js,设置基准 URL:

// playwright.config.js
module.exports = {
  use: {
    baseURL: 'http://localhost:5173',  // ← 改成你的开发服务器地址
  },
};

创建 tests/home-page.spec.js

// tests/home-page.spec.js
const { test, expect } = require('@playwright/test');

test('has title', async ({ page }) => {
  await page.goto('/'); // 访问首页

  // 断言标题包含 "Vite App"
  await expect(page).toHaveTitle(/Vite App/);
});

test('shows hello world', async ({ page }) => {
  await page.goto('/');

  const heading = await page.getByText('Hello World');
  await expect(heading).toBeVisible();
});

运行 E2E 测试

npx playwright test

你会看到浏览器自动打开、点击、验证!


🔄 第六步:集成到开发流程(保存自动测)

让你在开发时实时看到测试结果。

Vue + Vitest 用户

npm run test -- --watch

React + Jest 用户

npm run test:watch

现在每当你修改组件或测试文件并保存,测试就会自动重新运行!


🚀 第七步:提交时自动检查(Git Hook)

防止未通过测试的代码被提交。

使用 Husky + lint-staged

npm install -D husky lint-staged

启用 Git Hooks:

npx husky install
npm set-script prepare "husky install"

添加提交前钩子:

npx husky add .husky/pre-commit "npm test"

现在当你运行:

git add .
git commit -m "feat: add hello world"

会先自动运行所有测试,只有测试通过才能提交!


💡 常见问题与解决方案

问题原因解决方法
Cannot find module '@testing-library/react'没安装依赖npm install
Test environment not definedJest 缺少配置检查 testEnvironment: 'jsdom'
SyntaxError: Cannot use import outside moduleBabel 配置缺失确保有 .babelrc 或使用 Vite 插件
Element not found文本拼错或组件未渲染检查大小写、空格、异步加载
Playwright 报错 browserType.launch: Failed to launch缺少系统依赖运行 npx playwright install-deps

📌 总结 checklist

✅ 你现在已完成:

步骤是否完成
创建项目(Vue/React + Vite)
安装测试工具(Vitest/Jest + Testing Library)
编写第一个测试用例
成功运行测试并看到 PASS
添加快照测试
运行 E2E 测试(Playwright)
设置保存自动运行测试
提交代码前自动检查测试

🎁 附加资源

类型推荐链接
Testing Library 官网testing-library.com
Jest 中文文档jestjs.io/zh-Hans/
Playwright 教程playwright.dev
免费视频课(B站)搜索 “前端自动化测试入门”
GitHub 模板项目github.com/your-name/v…(可自行创建)

结语

🔥 “自动化测试不是高手专属,而是每个开发者走向专业的起点。”

你现在拥有的能力是:

🧠 知道如何给任意组件写测试
🛠️ 能独立搭建测试环境
🛡️ 让代码在每次改动后自动自检

这比大多数初级开发者都强!


🎯 下一步建议:

  1. 给你现有的项目加一个测试
  2. 把这份手册分享给朋友
  3. 在 GitHub 项目中加上 🟢 tests passing 徽章