如何为插件编写文档和测试用例

解读

在国内一线/二线大厂的 ESLint 方向面试里,这道题通常出现在第二轮“深挖工程化落地”环节。面试官想验证三件事:

  1. 你是否真正发布并维护过社区或内部插件,而不是只会用别人写好的规则;
  2. 你是否能把“可维护性”拆成文档、测试、CI 三板斧,并给出可落地的国内最佳实践;
  3. 你是否熟悉国内研发流程(GitLab MR、钉钉/飞书机器人、npm 私服、CI 配额限制),能把 ESLint 插件无缝嫁接到现有体系。
    回答时切忌只贴官方链接,而要给出“目录结构、脚本、示例、断言、覆盖率门禁、中文 README、CHANGELOG 规范”六位一体的完整方案,并解释每个环节在真实项目中的成本与收益。

知识点

  1. 插件目录规范:
    • lib/rules 存放规则实现,每文件默认导出一个 create(context) 函数;
    • docs/rules 存放对应 markdown,文件名与规则名保持一致,方便脚本自动生成索引;
    • tests/lib/rules 存放单测文件,命名必须是 <规则名>.test.js,以便 jest/eslint-internal-test 自动收集。
  2. 官方测试工具:
    • RuleTester 是 eslint 内置的“白盒”断言类,内部使用 espree 解析,支持 errors、output、options、settings、filename 五类字段;
    • 必须覆盖有效 invalid 用例的 messageId、data、fix,以及无效 valid 用例的“零误报”。
  3. 文档写作套路:
    • 标题、规则等级、fix 能力、兼容版本、背景动机、正确示例、错误示例、配置项表格、异常场景、关闭理由;
    • 中文 README 必须给出“私服安装”命令,防止候选人在内网无法拉包;
    • 提供 VS Code settings.json 片段,降低接入门槛。
  4. 覆盖率与门禁:
    • 国内 GitLab CI 通常单测配额 30 min,需把 jest --coverage 与 eslint-plugin-jest 搭配,把阈值锁到 100% branches;
    • 使用 nyc 或 c8 生成 lcov,配合钉钉机器人把报告推送到群,满足“可视化 KPI”。
  5. 自动化脚本:
    • npm run new-rule 自动创建四件套:规则骨架、测试文件、doc 模板、index 导出;
    • npm run update:readme 根据 docs/rules 自动生成目录,避免手工维护导致链接失效。
  6. 发版与回滚:
    • 采用 changesets 或 standard-version 自动生成中文 CHANGELOG,保证 MR 可追溯;
    • 私服使用 verdaccio 或 cnpm,发布前通过 npm pack --dry-run 检查 files 字段,避免把测试夹带进去。

答案

下面以“禁止 console 后未加说明注释”这条内部规则 no-console-without-comment 为例,给出可落地的文档与测试方案。
目录结构:
my-eslint-plugin/
├─ lib/rules/no-console-without-comment.js
├─ tests/lib/rules/no-console-without-comment.test.js
├─ docs/rules/no-console-without-comment.md
├─ README.md
├─ CHANGELOG.md
├─ package.json
└─ scripts/new-rule.js

  1. 规则实现(lib/rules/no-console-without-comment.js)
module.exports = {
  meta: {
    type: 'suggestion',
    docs: {
      description: 'require comment after console statement',
      category: 'Best Practices',
      recommended: true,
      url: 'https://git.company.com/eslint-plugin/-/blob/main/docs/rules/no-console-without-comment.md'
    },
    fixable: null,
    schema: [],
    messages: {
      missingComment: 'Expected inline comment to explain why console is used here.'
    }
  },
  create(context) {
    return {
      CallExpression(node) {
        const callee = node.callee;
        if (
          callee.type === 'MemberExpression' &&
          callee.object.name === 'console'
        ) {
          const nextToken = context.getSourceCode().getTokenAfter(node);
          if (!nextToken || nextToken.type !== 'Line' || !nextToken.value.startsWith('//')) {
            context.report({
              node,
              messageId: 'missingComment'
            });
          }
        }
      }
    };
  }
};
  1. 测试用例(tests/lib/rules/no-console-without-comment.test.js)
const { RuleTester } = require('eslint');
const rule = require('../../../lib/rules/no-console-without-comment');

const tester = new RuleTester({ parserOptions: { ecmaVersion: 2022 } });

tester.run('no-console-without-comment', rule, {
  valid: [
    'console.log("debug"); // for local debug',
    'window.console.error("oops"); // sentry fallback'
  ],
  invalid: [
    {
      code: 'console.info("hi")',
      errors: [{ messageId: 'missingComment' }]
    },
    {
      code: 'console.warn("oops"); /* block comment */',
      errors: [{ messageId: 'missingComment' }]
    }
  ]
});

跑 npm test 后应看到 4 passing,nyc coverage 100%。

  1. 文档(docs/rules/no-console-without-comment.md)
# no-console-without-comment

禁止在 console 语句后缺少解释性注释,避免调试代码被无意识地提交到生产。

## 等级

warning(可升级为 error)

## Fix

该规则无自动修复。

## 正确示例

```js
console.log('当前用户ID', uid); // 本地调试,上线前需删除

错误示例

console.log('当前用户ID', uid);

关闭理由

仅在紧急线上排错分支可临时关闭:

{
  "rules": {
    "@company/no-console-without-comment": "off"
  }
}

4. 根 README.md  
```markdown
# @company/eslint-plugin

## 安装(内网私服)

```bash
npm i -D @company/eslint-plugin --registry=http://npm.company.com

使用

{
  "extends": ["plugin:@company/recommended"]
}

规则列表

<!-- AUTO GENERATED START -->
规则描述fixable
no-console-without-commentconsole 后必须加注释否
<!-- AUTO GENERATED END -->

5. 自动化脚本(scripts/new-rule.js 节选)  
```javascript
const ruleName = process.argv[2];
fs.writeFileSync(`lib/rules/${ruleName}.js`, ruleTemplate(ruleName));
fs.writeFileSync(`tests/lib/rules/${ruleName}.test.js`, testTemplate(ruleName));
fs.writeFileSync(`docs/rules/${ruleName}.md`, docTemplate(ruleName));
execSync('npm run update:readme');

执行 node scripts/new-rule.js no-alert 即可一键生成四件套。

  1. CI 门禁(.gitlab-ci.yml 节选)
test:
  script:
    - npm test
    - npx c8 --reporter=lcov npm test
    - npx lcov-total lcov.info --gte 100
  coverage: '/Lines\s*:\s*(\d+\.\d+)%/'
  artifacts:
    reports:
      coverage_report:
        coverage_format: lcov
        path: lcov.info

当覆盖率低于 100% 或测试失败,MR 无法合并,符合国内“质量红线”要求。

拓展思考

  1. 如果规则需要跨语言提示(如 Vue 模板里也有 console),可把 parser 切换为 vue-eslint-parser,并在测试用例里增加 filename: 'test.vue' 的用例,验证多语法树场景。
  2. 对于“可修复”规则,务必在测试里同时验证 output 与 range,防止中文输入法全角空格导致 fix 后列错位;国内常见坑是 Windows 开发者 git autocrlf 不同造成断言失败,可在 .gitattributes 强制 * text=auto eol=lf。
  3. 大型 monorepo 里子包依赖版本不同,需要在 CI 里加 matrix 测试 eslint@7、eslint@8、eslint@9,保证插件的 AST 访问兼容性;同时把 lock 文件拆成 pnpm-workspace.yaml,减少私服拉取时间。
  4. 文档国际化:若团队有外籍员工,可用 remark-lint 统一中英文标点,并写一份 en-US 版,发布时通过 crowdin 或自研脚本同步,避免“中文双引号”在英文系统渲染为乱码。
  5. 灰度与回滚:在私服发布 beta 标签后,通过 @company/eslint-plugin@beta 在试点仓库跑 24h,收集控制台报错;若误报率 >1% 立即回滚,并生成 incident 报告推送到飞书群,形成闭环。