如何测试“AI”重构的“等效性”?
解读
国内前端面试中,面试官提出“AI 重构等效性”并不是让你写 AI 算法,而是考察两点:
- 能否把“AI 重构”抽象成一次黑盒函数调用——输入旧代码,输出新代码;
- 能否用 Jest 体系把“新旧代码行为一致”这件事自动化、可回归、可集成到 CI。
因此,核心考点是“用 Jest 做黑盒回归测试”的能力,同时兼顾国内真实工程约束:代码量大、CI 资源有限、需要快照、需要覆盖率兜底、需要并行提速。
知识点
- 黑盒模型:把旧模块导出视为“黄金 Master”,新模块视为“Candidate”,二者在同一组输入下必须输出相同结果。
- Jest 快照机制:对复杂对象、React 组件、AST、字符串 diff 结果做序列化比对,一行 expect 即可断言。
- 测试分层:
- 单元级:对纯函数、工具库做“亿级”输入的 property-based 测试(fast-check)。
- 集成级:对组件或接口做“千级”输入的自动化 e2e 快照。
- 覆盖率门槛:在 jest.config.js 里设 coverageThreshold,重构后只能升不能降。
- 并行与缓存:国内 GitLab CI 跑在 4C8G 容器,开 --maxWorkers=50% 配合 jest --cache 能把 10min 压到 2min。
- 伪随机种子:AI 重构若带随机性(如打乱 className),在测试文件顶部用 jest.mock 把 Math.random、Date.now 全部 mock 成固定种子,保证快照稳定。
- 国内合规:若 AI 重构涉及 GPL 代码片段,需用 jest-worker 起子进程隔离,避免主进程被“传染”开源协议。
答案
下面给出可直接落地的 Jest 方案,分五步完成“等效性”验证。
第一步:建立“双包”结构
src/
utils/ # 旧实现
utils.ai/ # AI 重构后的新实现,文件名、导出签名保持一致
第二步:写黑盒测试用例
// __tests__/equivalence.spec.js
import { old } from '../src/utils';
import { new as candidate } from '../src/utils.ai';
import fc from 'fast-check';
describe('AI 重构等效性', () => {
test('纯函数对等性 - 亿级随机输入', async () => {
await fc.assert(
fc.property(
fc.tuple(fc.string(), fc.integer(), fc.boolean()),
([s, n, b]) => {
expect(candidate(s, n, b)).toStrictEqual(old(s, n, b));
}
),
{ numRuns: 1_0000_0000, verbose: true }
);
});
test('React 组件快照对等性', () => {
const treeOld = renderer.create(<OldButton>提交</OldButton>).toJSON();
const treeNew = renderer.create(<NewButton>提交</NewButton>).toJSON();
expect(treeNew).toMatchSnapshot();
expect(treeNew).toEqual(treeOld);
});
});
第三步:覆盖率回归
// jest.config.js
module.exports = {
testMatch: ['**/__tests__/**/*.spec.js'],
collectCoverageFrom: [
'src/utils/**/*.{js,jsx,ts,tsx}',
'!src/utils.ai/**/*' // 旧代码已稳定,只盯新代码
],
coverageThreshold: {
global: {
branches: 95,
functions: 95,
lines: 95,
statements: 95
}
}
};
第四步:CI 集成(GitLab 国内公网 Runner)
# .gitlab-ci.yml
test:ai-equivalence:
stage: test
image: node:18-alpine
script:
- npm ci --registry=https://registry.npmmirror.com
- npx jest --ci --maxWorkers=50% --coverage --silent
coverage: '/All files[^|]*\|[^|]*\s+([\d\.]+)/'
artifacts:
reports:
coverage_report:
coverage_format: cobertura
path: coverage/cobertura-coverage.xml
第五步:watch 模式本地二次确认
npm run test:ai -- --watchAll=false --updateSnapshot
若快照 diff 仅顺序变化,用 jest-serializer-path 做排序后再快照;若 diff 真实存在,打回 AI 重新训练。
拓展思考
- 大文件极限:国内某电商 2W 行 reducer 被 AI 重构成切片模型,Jest 单测跑 40min 超时。解法是把文件拆成 200 段,用 jest.shard 拆到 8 个 Job 并行,总时长压到 5min。
- 运行时行为:AI 重构后若把同步 ajax 改成异步,黑盒测试仍通过但线上闪屏。需要再补一层“性能等效”——用 jest-performance 断言 FCP、LCP 差距 < 5%。
- 合规审计:国内银行要求“AI 生成代码必须可溯源”。在测试报告里用 jest-html-reporters 输出每条用例对应的旧文件 hash、新文件 hash,留存 5 年备查。
- 灰度放量:通过 jest-environment-node 把等效性测试封装成 npm 包,下发到各业务线作为 pre-commit 钩子,实现“重构不到测试通过不准 push”的强制门禁。