如何为 Watch 模式增加“语音播报”结果?
解读
面试官想确认三件事:
- 你是否真的用过 Jest 的 watch 模式,知道它在终端里会反复触发“run start / run finish”事件;
- 你是否理解 Jest 的插件化扩展点(Reporter、globalSetup、watchPlugins);
- 在真实企业场景里,你能否把“测试结果”与“语音播报”低成本、跨平台地串起来,而不污染主干流程、也不阻塞测试速度。
国内面试里,这道题常作为“开放型设计题”出现,重点不在“写出完整代码”,而在“思路闭环 + 边界考虑 + 可落地”。如果你能给出一条“npm 安装即可用”的链路,并说明如何兼容 Windows/Mac、CI 环境静音、以及 watch 模式高频触发的节流策略,就能拿到高分。
知识点
- Jest Reporter 接口:只要一个 class 实现 onRunStart/onRunComplete 方法,在 jest.config.js 里配进 reporters 数组即可被回调。
- node-speaker / say / @google-cloud/text-to-speech 等 TTS 库:开发机常用 say(macOS)、powershell(Win)、edge-tts(国内离线方案)。
- watch 与 non-watch 的区分:通过 process.env.npm_config_watch 或 reporter 的 contexts 判断,避免 CI 环境误播报。
- 并发与节流:watch 模式可能 1~2 秒就跑一次,需要“失败才播”或“防抖 3 秒”策略,防止语音轰炸。
- 国内云桌面/无声卡服务器:提前检测 $DISPLAY 或 aplay 命令是否存在,若无声卡则降级为“系统通知”或“钉钉机器人”。
- 工程化:把 reporter 抽成独立包(jest-speaker-reporter),在 package.json 里加配置字段,如 { "speaker": { "onlyFailure": true, "locale": "zh-CN" } },方便不同项目按需开启。
答案
下面给出一条“零配置即可用”的最小闭环,兼顾 Windows/Mac 以及 CI 静音场景,可直接在面试白板上写出来。
-
安装依赖
npm i -D jest-speaker-reporter cross-spawn -
新建 my-speaker-reporter.js
const spawn = require('cross-spawn'); const os = require('os'); class SpeakerReporter { constructor(globalConfig, options) { this._globalConfig = globalConfig; this._onlyFailure = options.onlyFailure !== false; this._locale = options.locale || 'zh-CN'; // 无声卡或 CI 直接禁用 this._mute = !!process.env.CI || !this._hasSpeaker(); } _hasSpeaker() { if (os.platform() === 'win32') return true; // PowerShell 始终可用 if (os.platform() === 'darwin') return true; // say 可用 return false; // Linux 需额外检测 aplay,这里简化 } onRunComplete(contexts, results) { if (this._mute) return; if (this._onlyFailure && !results.numFailedTests) return; const fail = results.numFailedTests > 0; const text = fail ? `测试失败,共 ${results.numFailedTests} 个用例未通过` : `测试全部通过,共 ${results.numTotalTests} 个用例`; this._speak(text); } _speak(text) { const cmd = os.platform() === 'win32' ? 'PowerShell' : 'say'; const args = os.platform() === 'win32' ? ['-Command', `Add-Type –AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak('${text}');`] : ['-v', this._locale === 'zh-CN' ? 'Ting-Ting' : 'Alex', text]; spawn(cmd, args, { stdio: 'ignore' }); } } module.exports = SpeakerReporter; -
在 jest.config.js 里声明
module.exports = { reporters: [ 'default', ['<rootDir>/my-speaker-reporter.js', { onlyFailure: true, locale: 'zh-CN' }] ] }; -
运行
npm test -- --watch
当用例失败时会听到中文女声播报“测试失败,共 X 个用例未通过”;全部通过则保持安静,避免打扰。
这样即完成“watch 模式语音播报”需求,代码量 <60 行,无原生依赖,符合国内开发机环境,也考虑了 CI 静音和节流策略。
拓展思考
- 如果团队使用 Linux 云桌面,可预装 edge-tts 命令行工具,把 _speak 方法换成 edge-tts --text "xxx" --write-media - | aplay,实现离线中文播报。
- 对于 monorepo 场景,可在 reporter 里读取 JEST_WORKER_ID,只在主线程(workerId === 1)播报一次,防止 8 核并行时重复朗读。
- 把 reporter 发成 npm 包并接入公司私有仓库,再配套一个 jest-watch-speaker 的 watchPlugin,用户可在 watch 菜单里按“s”键随时开关语音,体验更佳。
- 考虑夜间加班场景,可读取系统时间 22:00-08:00 自动切换为“系统通知横幅 + 静音”,避免影响他人。
- 语音只是“结果通知”的一种形式,同一套 reporter 还可以扩展为企业微信 Webhook、飞书卡片、甚至 RGB 灯带控制,形成“测试状态可视化”矩阵,凸显你在工程化与开发者体验上的深度思考。