如何为暗黑模式切换生成“多主题”快照?
解读
在国内前端面试中,暗黑模式(Dark Mode)已成为 B 端与 C 端产品的“标配”,面试官通过此题考察三点:
- 你是否理解 Jest 快照的本质(序列化 DOM 或组件树后做字符串 Diff);
- 你是否能把“主题”这一运行时变量,转化为“静态”快照输入;
- 你是否能在不污染生产代码的前提下,用 Jest 生态工具低成本地一次性生成并维护多份主题快照。
很多同学直接回答“把主题变量写死再 snapshot”,这只能得 30 分;真正的难点在于“一份测试文件、多套主题、零配置切换、快照命名不冲突、CI 可并行”。面试官期待听到“参数化测试 + 自定义序列化器 + 快照命名策略”的组合拳。
知识点
- snapshotSerializers:自定义序列化逻辑,把“主题类名”或“CSS 变量”一起打进快照。
- describe.each / test.each:官方参数化能力,避免手写 for 循环。
- toMatchSnapshot 的 snapshotName 参数:动态拼接主题后缀,防止同名冲突。
- jest.isolateModules:让同一组件在不同主题下重新 require,隔离副作用。
- React/Vue 官方测试工具(@testing-library/react、@vue/test-utils)的“渲染容器”机制,支持传入 class 或 data-theme 强制切换主题。
- CSS-in-JS 库(styled-components、emotion、@vanilla-extract)的 ThemeProvider,可在同一 Jest 进程内通过“内存样式表”切换主题,无需真实浏览器。
- 国内常见工程化约束:Monorepo + Rush/pnpm,快照必须位于 tests/snapshots 目录,且需支持 Windows 路径,因此序列化器里要对路径做 normalize。
答案
下面给出一份可直接落地的 React + styled-components 示例,Vue 思路完全一致,只需把渲染器换成 @vue/test-utils。
src
├─ components
│ └─ Button.jsx
└─ __tests__
├─ Button.dark.test.jsx
└─ __snapshots__
- 安装依赖
pnpm add -D jest @jest/globals @testing-library/react styled-components jest-styled-components
- 自定义序列化器(可选,但推荐)
// jest.snapshot.serializer.js
const path = require('path');
module.exports = {
test: val => val && val._isStyledComponent,
print: (val, serialize) => {
// 把随机 className 替换成稳定名称,防止哈希变化导致快照抖动
const stable = val.toString().replace(/sc-[a-zA-Z0-9]+/g, 'sc-stable');
return stable;
},
};
- 在 jest.config.js 注册
module.exports = {
snapshotSerializers: ['<rootDir>/jest.snapshot.serializer.js'],
testEnvironment: 'jsdom',
};
- 参数化测试文件
// Button.dark.test.jsx
import React from 'react';
import { render } from '@testing-library/react';
import styled, { ThemeProvider } from 'styled-components';
import '@testing-library/jest-dom';
// 主题配置
const lightTheme = { bg: '#fff', color: '#000' };
const darkTheme = { bg: '#000', color: '#fff' };
// 待测组件
const Button = styled.button`
background: ${p => p.theme.bg};
color: ${p => p.theme.color};
`;
// 参数化:主题名 + 主题对象
describe.each([
['light', lightTheme],
['dark', darkTheme],
])('Button %s theme', (themeName, theme) => {
it('matches snapshot', () => {
const { container } = render(
<ThemeProvider theme={theme}>
<Button>Click</Button>
</ThemeProvider>
);
// 显式给快照加后缀,防止同名
expect(container.firstChild).toMatchSnapshot(`button-${themeName}`);
});
});
- 运行
pnpm jest Button.dark.test.jsx --updateSnapshot
生成的快照文件:
__snapshots__
├─ Button.dark.test.jsx.snap
内容示例:
exports[`button-light 1`] = `
.sc-stable {
background: #fff;
color: #000;
}
`;
exports[`button-dark 1`] = `
.sc-stable {
background: #000;
color: #fff;
}
- 集成到 CI 在 GitHub Actions / GitLab CI 里加一步:
- run: pnpm jest --ci --coverage --updateSnapshot
若快照变更,MR 会高亮 Diff,Code Review 时一眼看出主题色值是否符合设计规范。
拓展思考
- 如果项目使用 Tailwind CSS,暗黑模式靠 class="dark" 切换,可把 render 放在两个不同容器:
const light = render(<div className="light"><Button /></div>);
const dark = render(<div className="dark"><Button /></div>);
然后用 prettyDOM(light.container) 生成快照,思路完全一致。
-
当主题数量爆炸(>10 套)时,用
test.concurrent并行渲染,配合jest --maxWorkers=50%可让 20 套主题快照在 3s 内跑完,满足国内“流水线 5 分钟”硬指标。 -
快照不是银弹,颜色值这种“视觉属性”建议再加一层
jest-image-snapshot做像素级比对,防止仅校验 CSS 文本而漏掉浏览器实际渲染差异。 -
对于微前端场景,主应用和子应用主题可能不同步,可在快照序列化器里把“CSS 变量实际计算值”打印出来,确保子应用独立发布时不会破坏主应用暗黑模式。
-
最后,务必在 CONTRIBUTING.md 里写明:“更新主题 token 后需同步执行
pnpm test:update-snapshot”,否则下一次 MR 会因快照失效被打回,这是国内大厂 Code Review 的“红线”之一。