前端单元测试:Jest 与 Testing Library 实战
MrSmy Lv5

写测试最难的不是”怎么断言”,而是”测什么”。我见过两种极端:一种是只测工具函数(覆盖率 30%,但业务流程完全没保护),另一种是每个组件都写测试(改了 UI 就要改 20 个测试文件,最后大家集体删除)。

这篇讲我们实际的落地方式:测行为,不测实现。

配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// jest.config.js
module.exports = {
testEnvironment: 'jsdom',
setupFilesAfterEach: ['<rootDir>/test/setup.js'],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
'\\.(css|less|scss)$': 'identity-obj-proxy',
'\\.(png|jpg|svg)$': '<rootDir>/test/__mocks__/fileMock.js',
},
collectCoverageFrom: [
'src/**/*.{js,jsx,ts,tsx}',
'!src/**/*.d.ts',
'!src/**/index.ts',
'!src/main.tsx',
],
coverageThreshold: {
global: {
branches: 60,
functions: 60,
lines: 70,
statements: 70,
},
},
}
1
2
3
4
5
// test/setup.js
import '@testing-library/jest-dom'

// 只 mock 真正的外部依赖
global.fetch = jest.fn()

**不要把覆盖率阈值设到 90%**。我们试过,结果是大家写了一堆 expect(true).toBe(true) 来凑数。60-70% 是”能跑通主要流程”的合理水平。

三层测试的分工

层级 测什么 数量 速度
纯函数 / utils 边界条件、异常输入 多 毫秒
组件 渲染、交互、状态变化 中 百毫秒
页面 / 集成 用户完整流程 少 秒

纯函数最值得测——它们没有副作用,断言简单,且往往是业务逻辑的核心(金额计算、日期格式化、权限判断)。

1
2
3
4
5
6
7
8
9
// utils/price.js
export function calcDiscount(price, level) {
if (price < 0) throw new Error('价格不能为负')
const rates = { normal: 1, silver: 0.95, gold: 0.9 }
const rate = rates[level]
if (!rate) throw new Error(`未知会员等级: ${level}`)
// 保留两位小数,避免浮点误差
return Math.round(price * rate * 100) / 100
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// utils/price.test.js
import { calcDiscount } from './price'

describe('calcDiscount', () => {
it.each([
[100, 'normal', 100],
[100, 'silver', 95],
[100, 'gold', 90],
[99.99, 'gold', 89.99],
[0, 'gold', 0],
])('价格 %p 等级 %p 应为 %p', (price, level, expected) => {
expect(calcDiscount(price, level)).toBe(expected)
})

it('负数价格应该抛错', () => {
expect(() => calcDiscount(-1, 'normal')).toThrow('价格不能为负')
})

it('未知等级应该抛错', () => {
expect(() => calcDiscount(100, 'diamond')).toThrow(/未知会员等级/)
})
})

it.each 让表格式的用例更紧凑。注意浮点问题:99.99 * 0.9 = 89.99100000000001,所以要用 Math.round 处理,测试里也要用精确值断言。

这条测试曾经救过我一次:需求改成”折扣后四舍五入到分”,原来的 toFixed(2) 有银行家舍入问题(1.005.toFixed(2) === '1.00'),测试立刻失败,发现是线上少收了钱。

组件测试:从用户视角

React 组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// components/SearchBox.jsx
export function SearchBox({ onSearch }) {
const [value, setValue] = useState('')

return (
<form
onSubmit={(e) => {
e.preventDefault()
onSearch(value.trim())
}}
>
<input
aria-label="搜索关键词"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
<button type="submit">搜索</button>
</form>
)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// components/SearchBox.test.jsx
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { SearchBox } from './SearchBox'

it('提交时回传去掉首尾空格的关键词', async () => {
const onSearch = jest.fn()
render(<SearchBox onSearch={onSearch} />)

const input = screen.getByLabelText('搜索关键词')
await userEvent.type(input, ' vue3 ')
await userEvent.click(screen.getByRole('button', { name: '搜索' }))

expect(onSearch).toHaveBeenCalledWith('vue3')
expect(onSearch).toHaveBeenCalledTimes(1)
})

三个关键点:

1. 用 getByRole / getByLabelText 而不是 getByTestId

前者是”用户能感知到的查询方式”(按钮的文本、输入框的 label),也更接近可访问性要求。用 testid 的测试在重构 DOM 结构时很容易失效,但用 role 的测试不会——因为它测的是行为。

2. 用 userEvent 而不是 fireEvent

userEvent 会模拟真实的浏览器行为序列(focus、keydown、input、keyup),fireEvent.change 只是直接触发事件。后者会漏掉很多真实交互中的 bug。

3. 只断言”输出”,不断言”内部状态”

1
2
3
4
5
// 不要这样:测了实现细节
expect(wrapper.state('value')).toBe('vue3')

// 应该这样:测了行为结果
expect(onSearch).toHaveBeenCalledWith('vue3')

不测内部状态的原因是:状态管理方式会变(useState → useReducer → Redux),但”提交时回传什么”不会变。

异步测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// components/UserProfile.jsx
export function UserProfile({ userId }) {
const [user, setUser] = useState(null)
const [error, setError] = useState(null)

useEffect(() => {
fetch(`/api/users/${userId}`)
.then((r) => (r.ok ? r.json() : Promise.reject(new Error(r.status))))
.then(setUser)
.catch(setError)
}, [userId])

if (error) return <div role="alert">加载失败</div>
if (!user) return <div>加载中...</div>
return <div>{user.name}</div>
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
it('加载成功后显示用户名', async () => {
global.fetch.mockResolvedValueOnce({
ok: true,
json: async () => ({ name: '张三' }),
})

render(<UserProfile userId={1} />)
expect(screen.getByText('加载中...')).toBeInTheDocument()

expect(await screen.findByText('张三')).toBeInTheDocument()
})

it('接口失败时显示错误', async () => {
global.fetch.mockResolvedValueOnce({ ok: false, status: 500 })

render(<UserProfile userId={1} />)
expect(await screen.findByRole('alert')).toHaveTextContent('加载失败')
})

findBy* 会等待(默认 1000ms),getBy* 是同步立即查询。异步场景用错会导致”没找到元素”的报错。

警告:act() 警告

1
Warning: An update to UserProfile inside a test was not wrapped in act(...)

意思是”状态更新发生在测试不感知的地方”。常见原因:

  1. 用了 await 之外的异步(比如忘了 await 一个 promise)
  2. 定时器相关的更新(用 jest.useFakeTimers())

大多数情况下用 findBy* / waitFor 就能避免。不要靠加 act() 消除警告,要找到真正的原因。

Mock 的边界

1
2
3
4
5
6
7
8
// ✅ mock 外部依赖
jest.mock('@/api/user')
jest.mock('next/router', () => ({
useRouter: () => ({ push: jest.fn(), query: {} }),
}))

// ❌ 不要 mock 自己写的业务模块
jest.mock('@/utils/format') // 这样测试的是"mock 的行为",不是真实行为

判断标准:这个模块是不是”我不想在测试里真正执行”的。网络请求、浏览器 API、时间、随机数——这些该 mock。业务逻辑不该 mock。

时间 mock:

1
2
3
4
5
6
7
8
9
10
beforeEach(() => {
jest.useFakeTimers().setSystemTime(new Date('2021-10-24T12:00:00Z'))
})
afterEach(() => {
jest.useRealTimers()
})

it('30 分钟内显示"刚刚"', () => {
expect(formatTime('2021-10-24T11:45:00Z')).toBe('刚刚')
})

不加时间 mock 的时间测试一定会在某天失败(比如跨年、夏令时)。

覆盖率怎么用

1
jest --coverage
1
2
3
4
5
File           | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
---------------|---------|----------|---------|---------|-------------------
All files | 71.24 | 62.18 | 68.42 | 72.05 |
utils/price.js| 100 | 100 | 100 | 100 |
utils/date.js | 82.35 | 66.67 | 71.43 | 83.33 | 24,31-35

**覆盖率是”发现盲区”的工具,不是”质量指标”**。

  • lines 覆盖率高但 branches 低 → 只测了正常路径,没测异常分支
  • 某个文件覆盖率是 0 → 要么没测,要么是死代码(可以删)
  • 覆盖率 100% 的模块 → 通常是最简单的模块,价值不高

我们的实际做法:CI 里只卡全局阈值(不低于 65%),并允许用 /* istanbul ignore next */ 排除真正的防御性代码(比如 switch 的 default 分支)。

但要求:每个 ignore 都要在 code review 时说明理由。不加约束的话,这个注释会变成”给覆盖率凑数的工具”。

不该写测试的场景

  • 纯样式组件(<div className="container">{children}</div>)—— 测了也是 expect(container).toBeInTheDocument()
  • 第三方库的封装(一层 export { Button } from 'antd')
  • 一次性脚本、迁移工具
  • 还没确定需求的原型

反过来,必须测的:

  • 金额、税率、积分计算
  • 权限判断(canEdit、canDelete)
  • 状态机流转(订单状态、支付状态)
  • 数据转换(后端 DTO → 前端模型)
  • 有复杂条件渲染的组件

性能

测试套件超过 2 分钟后,大家就不愿意在提交前跑了。

1
2
3
Test Suites: 42 passed
Tests: 318 passed
Time: 38.2s

优化手段:

1. 只跑相关测试

1
2
jest --watch
jest src/components/SearchBox

2. --maxWorkers

1
jest --maxWorkers=50%

CI 机器核数少时,并行反而更慢(进程切换开销)。

3. 避免大量 jest.mock 的模块扫描

1
2
// jest.config.js
modulePathIgnorePatterns: ['<rootDir>/dist/'],

4. 拆成多个 project 并行跑

巨型仓库可以把 packages/*/jest.config.js 分开,CI 里用 matrix 并行。

踩过的坑

1. toMatchSnapshot 的滥用

快照测试看起来很爽(一行代码测全部输出),但改样式后会产生大量”需要更新快照”的提示,最后大家都无脑 -u,快照就失去了意义。

我们的规则:快照只用于”输出结构稳定、内容不多”的场景(比如序列化后的配置、错误信息格式)。

2. getByText 匹配到多个元素

1
2
3
4
it('渲染列表', () => {
render(<List items={['A', 'A']} />)
screen.getByText('A') // Error: Found multiple elements
})

用 getAllByText 加断言数量,或者改 DOM 让每个元素有唯一标识。

3. 测试之间有共享状态

1
2
3
4
5
6
7
8
9
10
11
// ❌ 模块级变量在测试间共享
let users = []

beforeEach(() => {
users.push({ id: 1 }) // 第二个测试会看到 2 条
})

// ✅ 每次重置
beforeEach(() => {
users = []
})

或者更彻底:jest.resetModules() / 每个测试用独立实例。

4. 测试依赖执行顺序

Jest 默认并行跑测试文件,但同一文件内的测试是顺序执行的。依赖顺序的测试是设计问题——每个 it 都应该独立。

5. 覆盖率包含测试文件自身

1
2
3
4
collectCoverageFrom: [
'src/**/*.{js,ts}', // 只看 src
'!src/**/*.test.{js,ts}', // 排除测试自身
],

小结

单元测试的价值不在”证明代码正确”,而在”敢改代码”:

有测试 没有测试
重构后跑一遍就知道有没有坏 改完心里没底,只敢加代码不敢改
发现边界条件 bug 靠用户反馈
是活的文档 代码意图靠猜

三个实践原则:

  1. 测行为不测实现——用 role/label 查询,断言”输出”不断言”状态”
  2. 纯函数优先——覆盖率投入产出比最高
  3. 覆盖率是盲区探测器——不是 KPI

后来我们迁移到了 Vitest(2023 年底),测试代码几乎不用改——因为一直坚持”测行为”,所以不依赖具体的测试框架 API。这算是”测行为”带来的额外好处:测试可以迁移,而用例的价值不丢。

  • 本文标题:前端单元测试:Jest 与 Testing Library 实战
  • 本文作者:MrSmy
  • 创建时间:2021-10-24 20:33:00
  • 本文链接:https://fengyang.live/2021/10/24/前端单元测试:Jest与TestingLibrary实战/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!