You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jest项目提交单元测试文件时校验其目录名称?

校验Jest单元测试文件目录的可行方案

当然有现成的工具能实现这个需求,而且大多是你可能已经在项目里用到的ESLint生态工具,下面给你几个实用的方案:

方案一:用eslint-plugin-jest的内置规则(最省心)

这是官方维护的Jest ESLint插件,自带专门检查测试文件位置的规则,集成起来非常方便:

  • 首先安装依赖:
    npm install eslint-plugin-jest --save-dev
    # 或者用yarn
    yarn add eslint-plugin-jest -D
    
  • 然后在你的ESLint配置文件(比如.eslintrc.js或.eslintrc.json)里添加配置:
    module.exports = {
      // 引入jest插件
      plugins: ['jest'],
      rules: {
        // 开启测试文件目录检查规则,设置为error级别触发错误提示
        'jest/no-test-files-outside-test-directories': [
          'error',
          {
            testDirectory: '__tests__' // 指定唯一合法的测试目录
          }
        ]
      }
    };
    

这个规则会自动识别所有后缀为.test.js、.spec.js(包括TS文件)的测试文件,只要它们不在__tests__目录下,就会抛出明确的错误提示。

方案二:自定义ESLint规则(针对特定错误目录拦截)

如果你需要专门禁止__test__、_tests_这类容易打错的目录名,可以写一个简单的自定义规则:

  • 在项目里创建自定义规则文件,比如eslint-rules/no-wrong-test-dir.js:
    module.exports = {
      create: function(context) {
        // 定义要禁止的错误目录名
        const forbiddenDirs = ['__test__', '_tests_'];
        const filePath = context.getFilename();
        
        // 只检查测试文件
        if (filePath.match(/\.(test|spec)\.(js|ts)$/i)) {
          forbiddenDirs.forEach(dir => {
            if (filePath.includes(`/${dir}/`)) {
              context.report({
                message: `测试文件不能放在${dir}目录下,请使用__tests__目录`
              });
            }
          });
        }
        return {};
      }
    };
    
  • 接着在ESLint配置里引入这个自定义规则:
    module.exports = {
      rules: {
        'custom/no-wrong-test-dir': 'error'
      },
      plugins: {
        custom: {
          rules: {
            'no-wrong-test-dir': require('./eslint-rules/no-wrong-test-dir.js')
          }
        }
      }
    };
    

方案三:配合husky + lint-staged在提交前强制检查

为了确保没人能绕过检查提交不符合规范的文件,可以结合husky和lint-staged在代码提交前自动触发校验:

  • 安装依赖:
    npm install husky lint-staged --save-dev
    
  • 在package.json里添加如下配置:
    {
      "husky": {
        "hooks": {
          "pre-commit": "lint-staged"
        }
      },
      "lint-staged": {
        "**/*.{test,spec}.{js,ts}": [
          "eslint"
        ]
      }
    }
    

这样每次提交测试文件时,都会自动执行ESLint检查,一旦目录不符合要求就会直接阻止提交,从根源上避免错误。

内容的提问来源于stack exchange,提问作者Huan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 19:13:14