跳到主要内容

Jest 规则

eslint-plugin-jest 针对 Jest 测试框架的推荐规则,用于确保测试文件的语法和最佳实践符合 Jest 的要求,例如检查测试用例的命名、断言的使用等。

// .eslintrc.js

module.exports = {
extends: [
'plugin:jest/recommended',
'plugin:jest/style',
],
};
注意

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

推荐规则

规则名称错误级别配置选项描述
jest/expect-expectwarn-强制在测试中至少有一个 expect 断言
jest/no-alias-methodserror-禁止使用 Jasmine 的别名方法(如 toHaveBeenCalled 代替 toBeCalled
jest/no-commented-out-testswarn-禁止注释掉的测试代码
jest/no-conditional-expecterror-禁止在条件语句中使用 expect
jest/no-deprecated-functionserror-禁止使用已弃用的 Jest 函数
jest/no-disabled-testswarn-禁止使用 describe.skiptest.skip 禁用测试
jest/no-done-callbackerror-禁止在异步测试中使用 done 回调(推荐使用 Promise/async)
jest/no-exporterror-禁止从测试文件中导出内容
jest/no-focused-testserror-禁止提交 focused 测试(如 describe.onlytest.only
jest/no-identical-titleerror-禁止测试用例/描述块使用相同标题
jest/no-interpolation-in-snapshotserror-禁止在快照中使用字符串插值
jest/no-jasmine-globalserror-禁止使用 Jasmine 全局变量
jest/no-mocks-importerror-禁止手动从 jest-mocks 路径导入 mock 模块
jest/no-standalone-expecterror-禁止在测试块/钩子函数外使用 expect
jest/no-test-prefixeserror-强制使用规范的测试别名(如 test 代替 it
jest/valid-describe-callbackerror-强制 describe 回调函数的正确用法
jest/valid-expecterror-强制 expect 调用的有效性
jest/valid-expect-in-promiseerror-确保 Promise 中的 expect 被正确处理
jest/valid-titleerror-强制测试标题符合指定格式要求

风格

规则名称错误级别配置选项描述
jest/prefer-to-beerror-强制使用 toBe() 替代 toEqual() 进行原始类型值的断言(如数字、布尔值)
jest/prefer-to-containerror-强制使用 toContain() 替代 indexOf() 检查数组/字符串包含关系
jest/prefer-to-have-lengtherror-强制使用 toHaveLength() 替代直接访问 length 属性断言长度