如何对 Web Animations API 做“时间缩放”?
解读
面试官抛出此题,核心想验证三件事:
- 你是否真的“动过手”——Web Animations API 不是纸上谈兵;
- 你是否理解“时间”这一维度的可测试性——单元测试里最怕的就是 setTimeout、requestAnimationFrame 这类“真时间”;
- 你是否能把“时间缩放”与 Jest 的测试哲学(快、稳、可重复)结合起来,给出工程级方案。
国内大厂(阿里、腾讯、字节、美团)的面试现场,这道题常被用作“React 动效组件”或“可视化大屏项目”的延伸追问。答不到“把 6 秒动画压成 60 ms 跑完”这一层,基本会被判定为“只写过 demo”。
知识点
-
Web Animations API 的时间模型
- timeline:默认是 DocumentTimeline,起始时间 performance.timeOrigin,当前时间 performance.now()。
- animation.startTime、currentTime 以毫秒为单位,可写可读。
- 关键:currentTime 支持“CSS 数值”或“CSSNumericValue”,即可接受 calc、var,也可直接赋毫秒数。
-
Jest 的“假时间”能力
- jest.useFakeTimers({ now: 0, advanceTimers: false }) 把 global.performance.now、Date.now、setTimeout 等全部 Mock 掉。
- 提供 tick(ms)、runAllTimers、runOnlyPendingTimers 三种推进方式。
- 注意:jest-environment-jsdom 默认带 performance,但 timeline 仍走真时间,必须手动 Mock。
-
时间缩放(Time Scaling)的两种策略
a. 直接改 timeline——把 DocumentTimeline 换成自定义的 DocumentTimeline,其 currentTime 永远等于“真实时间 × 缩放因子”。
b. 不改 timeline,只改 animation——在测试里把 animation.updatePlaybackRate(scale) 或 animation.currentTime 手动乘系数。
策略 a 对业务代码零侵入,策略 b 对单测代码零侵入;国内团队 90% 场景用策略 b,因为“动画库已封装,改 timeline 成本太高”。 -
快照测试与可视化回归
- 时间缩放后,动画会在一帧内跳到终点,此时可拍“终态”快照。
- 若需“关键帧”快照,可在 tick(0)、tick(30)、tick(60) 三处分别拍,配合 jest-image-snapshot 做像素级回归。
-
并行与 watch 模式
- 时间缩放后动画同步执行,不再占用 6 s 真实时间,Jest 的 --maxWorkers 可放心开大,CI 机器成本直接打 1 折。
答案
下面给出“国内业务最常用、面试官最买账”的 30 行代码级方案,兼顾“零侵入业务”与“秒级跑完用例”。
// jest.setup.js —— 全局一次性配置
global.performance = {
...global.performance,
now: jest.fn(() => Date.now()), // 让 timeline 走到 fake time
};
// foo.test.jsx
import { render } from '@testing-library/react';
import React, { useEffect, useRef } from 'react';
jest.useFakeTimers({ now: 0, advanceTimers: false });
function SlideIn({ duration = 6000 }) {
const ref = useRef();
useEffect(() => {
const ani = ref.current.animate(
[{ transform: 'translateX(-100%)' }, { transform: 'translateX(0)' }],
{ duration, fill: 'both' }
);
// 生产环境走真时间,测试环境自动缩放
if (process.env.NODE_ENV === 'test') {
// 6 s 动画缩成 60 ms,缩放因子 0.01
ani.updatePlaybackRate(100); // 1 s 真实时间 = 100 s 动画时间
// 也可以直接改 currentTime,更直观:
// ani.currentTime = performance.now() * 100;
}
}, [duration]);
return <div ref={ref}>Hello Jest</div>;
}
test('SlideIn 在 60 ms 内完成动画', () => {
const { container } = render(<SlideIn />);
const target = container.firstChild;
// 初始态
expect(getComputedStyle(target).transform).toContain('-100');
// 把 60 ms 动画时间一次性跑完
jest.advanceTimersByTime(60);
// 终态
expect(getComputedStyle(target).transform).toContain('matrix(1, 0, 0, 1, 0');
});
要点拆解
- jest.useFakeTimers 把 performance.now 也纳入 Mock,确保 timeline 走到“假时间”。
- 在组件内部通过
process.env.NODE_ENV === 'test'判断,只做测试侧的时间缩放,业务代码无感知。 - 使用
updatePlaybackRate(100)把 6 s 动画压缩到 60 ms;也可手动设置 currentTime,效果等价。 - 用
jest.advanceTimersByTime(60)一次性推进,避免 runAllTimers 把后续轮询也跑完,保持用例隔离。 - 断言使用 getComputedStyle 而非快照,既快又稳;若项目有“像素级回归”要求,可把终态 DOM 拍快照或用 jest-image-snapshot 抓图。
拓展思考
-
如果动画库(如 framer-motion、react-spring)把 Web Animations API 封装在闭包里,拿不到 animation 实例怎么办?
→ 在测试入口用Object.defineProperty(Element.prototype, 'animate', { value: jest.fn(realAnimate) })做 spy,返回的 animation 对象再被统一加速即可。国内蚂蚁 AntV、字节 VisActor 都是这么玩。 -
需要测试“中间态”而非终态,如何精准控制?
→ 把 duration 设为 1000 ms,缩放因子 10,则 10 ms 真实时间对应 100 ms 动画时间;在 tick(0)、tick(5)、tick(10) 三处拍快照,可拿到 0%、50%、100% 关键帧,兼顾 CI 速度与回归粒度。 -
浏览器真机可视化测试(e2e)还要不要时间缩放?
→ 不需要。Playwright/Cypress 端用chrome DevTools Protocol的Animation.setPlaybackRate即可,把整页动画放慢或放快,与 Jest 单测形成“单元快、e2e 慢”的双层防护,国内美团外卖商家端就是这套组合。 -
会不会有“时间缩放导致 requestAnimationFrame 回调未触发”的坑?
→ 不会。jest.useFakeTimers 已把 rAF 也 Mock 掉,tick 会顺序触发所有 rAF 回调,只要保证 tick 步长小于 16 ms,就能模拟完整 60 FPS 帧序列,动画曲线与真机保持一致。
把以上四点吃透,面试现场可顺势展开“如何搭建可视化组件的单元 + e2e 双层质量门禁”,直接拿到“测试深度”评分项的满分。