使用 @babel/plugin-tester 编写单元测试

解读

在国内一线/二线前端面试中,Babel 插件开发能力已从“加分项”演变为“工程化必考题”。
“你会写插件吗?”之后,面试官往往追问:“你怎么保证插件正确性?”——@babel/plugin-tester 就是官方推荐的单测方案。
该题表面问“写单测”,实则考察:

  1. 是否熟悉 Babel 插件的输入输出模型(AST 级快照比对);
  2. 是否理解 plugin-tester 的默认断言策略与自定义钩子;
  3. 是否能在真实工程里落地(Monorepo、CI、覆盖率门禁)。
    答不出“快照怎么更新”“如何测报错”“如何测插件序”会被直接判定“只写过玩具插件”。

知识点

  1. @babel/plugin-tester 定位:零配置、基于 jest 快照的插件单测框架。
  2. 核心 API:
    • pluginTester(options): 注册一组用例;
    • options.plugin: 必填,插件函数或模块;
    • options.tests: 数组,元素可以是字符串(代码片段)或对象(含 snapshot、title、setup、teardown、error 等);
    • options.snapshot: 布尔,开启 jest 快照,默认 true;
    • options.babelOptions: 透传 babel.transform 的选项,如 presets、parserOpts;
    • options.formatResult: 自定义结果格式化,常用于去空格、去注释;
    • options.pluginOptions: 给插件传参,测不同配置分支。
  3. 测试策略:
    • 正向:输入 code → 期望 output 或快照;
    • 反向:输入 code → 期望抛出指定异常 message;
    • 边界:空文件、Syntax Error、保留区(leadingComments、ranges)完整性;
    • 插件序:把插件放入 preset,验证与其他插件的 AST 干扰。
  4. 国内落地细节:
    • jest 版本需 ≥26,否则快照序列化插件不兼容;
    • CI 中需加 --ci --updateSnapshot 策略,防止快照漂移;
    • 覆盖率门禁:nyc + jest,插件分支覆盖率≥90% 才能合并;
    • Monorepo 下把测试放在 tests 目录,与 src 同层,方便 lerna changeset 统一版本。

答案

以下示例实现一个“干掉 console.*”的插件,并给出完整单测。目录结构按国内主流 Monorepo 习惯:

packages/babel-plugin-drop-console
├── src
│ └── index.js
├── tests
│ └── index.test.js
└── package.json

src/index.js

module.exports = function({ types: t }) {
  return {
    name: 'drop-console',
    visitor: {
      CallExpression(path) {
        const callee = path.get('callee');
        if (
          callee.isMemberExpression() &&
          callee.get('object').isIdentifier({ name: 'console' })
        ) {
          path.remove();
        }
      }
    }
  };
};

tests/index.test.js

const pluginTester = require('@babel/plugin-tester').default;
const plugin = require('../src');

pluginTester({
  plugin,
  pluginName: 'drop-console',
  tests: [
    // 1. 基础正向
    {
      title: 'remove console.log',
      code: `console.log('hello'); foo();`,
      output: `foo();`
    },
    // 2. 快照模式(默认)
    `console.warn('warn');`, // 无 output 字段即走快照
    // 3. 反向测试
    {
      title: 'should throw when options.error is true',
      code: `console.error('oops');`,
      error: /drop-console does not allow console.error/,
      setup() {
        // 模拟插件配置分支
        plugin.visitor = () => ({
          CallExpression(path) {
            throw new Error('drop-console does not allow console.error');
          }
        });
      }
    },
    // 4. 边界:模板字面量
    {
      title: 'template literal with console',
      code: `console.log(\`foo\${bar}\`);`,
      output: '``;'
    }
  ]
});

运行

yarn jest __tests__/index.test.js

首次执行生成快照,后续若插件逻辑变更,jest -u 更新快照。CI 中配合

yarn jest --ci --coverage --coverageReporters=text-summary

若覆盖率低于 90%,Merge Request 自动拒绝。

拓展思考

  1. 如何测试“插件顺序”导致的 AST 污染?
    答:在 pluginTester 的 babelOptions.presets 里故意把 @babel/preset-react 放前面,观察插件是否把 JSXElement 误删。
  2. 如何测试“异步插件”?
    答:plugin-tester 暂不支持异步访问,需自行封装 babel.transformAsync,并用 jest 的 resolves/rejects 断言。
  3. 如何与 ESLint 插件联动?
    答:把 Babel 插件注册到 eslint-plugin-custom 的 parserServices,让单测同时跑 eslint rule,实现“编译+规约”一体化回归。
  4. 国内微前端场景:子应用独立构建,主应用统一 polyfill。
    答:在 plugin-tester 的 babelOptions 里注入 import('@babel/polyfill'),验证插件不会误删“关键引入语句”,防止线上白屏。