跳到主要内容

Vitest 规则

@vitest/eslint-plugin 是 Vitest 官方维护的 ESLint 插件,针对 Vitest 测试框架提供推荐规则,用于确保测试文件的语法和最佳实践符合 Vitest 的要求,例如检查测试用例的命名、断言的使用等。

配置​

Flat Config(ESLint v9+):

// eslint.config.js
// $ pnpm add -D @vitest/eslint-plugin
import vitest from '@vitest/eslint-plugin';

export default [
{
files: ['**/*.{test,spec}.{js,ts,jsx,tsx}'],
plugins: {
vitest,
},
rules: {
...vitest.configs.recommended.rules,
},
},
];

Legacy Config(ESLint v8 及以下):

// .eslintrc.js

module.exports = {
extends: [
'plugin:@vitest/legacy-recommended',
],
};
提示

在 Flat Config 中,规则以 vitest/ 为前缀(如 vitest/valid-title);在 Legacy Config 中,规则以 @vitest/ 为前缀(如 @vitest/valid-title)。

提示

若在 vitest.config.ts 中开启了 globals: true,可在 Flat Config 中声明全局测试 API,避免 no-undef 报错:

{
files: ['**/*.{test,spec}.{js,ts,jsx,tsx}'],
plugins: { vitest },
rules: { ...vitest.configs.recommended.rules },
languageOptions: {
globals: {
...vitest.environments.env.globals,
},
},
}
注意

在编写 Vitest 测试代码时,可以适当关闭一些规则,避免过于严格的检查影响开发效率。但是,仍然鼓励遵循这些规范,以提高代码质量和可维护性。

推荐规则​

以下规则由 vitest.configs.recommended(Legacy Config 中为 plugin:@vitest/legacy-recommended)默认开启:

规则名称错误级别配置选项描述
vitest/expect-expecterror-强制测试用例中至少有一个 expect 断言
vitest/no-commented-out-testserror-禁止注释掉的测试代码
vitest/no-conditional-expecterror-禁止在条件语句中使用 expect
vitest/no-disabled-testswarn-禁止使用 describe.skip / test.skip 等方式禁用测试
vitest/no-focused-testserror-禁止提交 focused 测试(如 describe.only / test.only)
vitest/no-identical-titleerror-禁止测试用例/描述块使用相同标题
vitest/no-import-node-testerror-禁止导入 node:test 模块,应使用 Vitest 提供的 API
vitest/no-interpolation-in-snapshotserror-禁止在快照中使用字符串插值
vitest/no-mocks-importerror-禁止手动从 __mocks__ 目录导入 mock 模块
vitest/no-standalone-expecterror-禁止在 it / test 块或钩子函数外使用 expect
vitest/no-unneeded-async-expect-functionerror-禁止为 resolves / rejects 断言包裹多余的 async 函数
vitest/prefer-called-exactly-once-witherror-优先使用 toHaveBeenCalledExactlyOnceWith 断言函数被精确调用一次且参数匹配
vitest/require-local-test-context-for-concurrent-snapshotserror-并发测试中使用快照断言时,必须使用局部测试上下文
vitest/valid-describe-callbackerror-强制 describe 回调函数的正确用法
vitest/valid-expecterror-强制 expect 调用的有效性
vitest/valid-expect-in-promiseerror-确保 Promise 中的 expect 被正确处理
vitest/valid-titleerror-强制测试标题符合指定格式要求

可选规则​

以下规则未包含在推荐配置中,可按需在 rules 中手动开启。使用 vitest.configs.all 可以 warn 级别开启全部规则:

规则名称建议级别配置选项描述
vitest/max-nested-describeerrormax限制 describe 的最大嵌套层数(如 { max: 3 })
vitest/no-alias-methodserror-禁止使用别名断言方法(如使用 toBeCalled 代替 toHaveBeenCalled)
vitest/no-conditional-testserror-禁止使用条件语句包裹测试逻辑
vitest/no-duplicate-hookserror-禁止在同一个测试套件中重复定义钩子函数
vitest/no-large-snapshotswarnmaxSize限制快照的大小与行数,保持快照文件可读
vitest/no-test-prefixeserror-禁止使用 x / f 前缀别名,应使用 .skip / .only
vitest/no-test-return-statementerror-禁止在测试回调中使用 return 语句返回值,应使用断言
vitest/prefer-hooks-on-topwarn-强制钩子函数位于 describe 块顶部
vitest/prefer-to-beerror-强制使用 toBe() 替代 toEqual() 进行原始类型值的断言(如数字、布尔值)
vitest/prefer-to-containerror-强制使用 toContain() 替代 indexOf() 检查数组/字符串包含关系
vitest/prefer-to-have-lengtherror-强制使用 toHaveLength() 替代直接访问 length 属性断言长度