【问题标题】:eslint ignore no-undef with certain folder with jesteslint 忽略带有玩笑的某些文件夹的 no-undef
【发布时间】:2020-04-17 02:23:44
【问题描述】:

我目前正在使用 jest 来测试我的 api 调用。我也使用 eslint 来检查我的测试中的代码,但是因为使用 just,我不需要定义诸如 test()expect() 之类的方法,所以当我运行 eslint 时,我会收到诸如

之类的错误
   4:1  error  'test' is not defined    no-undef
   8:3  error  'expect' is not defined  no-undef

但是对于我的笑话文件,例如index.test.js,我的代码将是

test('API test', async () => {
  const response = await axios.post('api call', {});
  const { status, statusText, message } = response;
  expect(status).toBe(400);
  expect(statusText).toBe('Bad Request');
  expect(message).toBe('No password.');
});

如前所述,我不需要定义test()expect。我正在阅读 eslint 文档,但我似乎没有看到一种可能的方法来只忽略某些文件而不检查这些规则。不过我还是想遵守其他规则。

提前感谢任何帮助建议。

附:我的.eslintrc 看起来像

{
  "parser": "babel-eslint",
  "extends": "eslint:recommended",
  "env": {
    "commonjs": true,
    "es6": true,
    "node": true,
    "browser": false
  },
  "parserOptions": {
    "ecmaFeatures": {
      "experimentalObjectRestSpread": true,
      "jsx": false
    },
    "sourceType": "module"
  },
  "globals": {
    "strapi": true
  },
  "rules": {
    "indent": ["error", 2, { "SwitchCase": 1 }],
    "linebreak-style": ["error", "unix"],
    "no-console": 0,
    "quotes": ["error", "single"],
    "semi": ["error", "always"],
    "multiline-ternary": ["error", "always"]
  }
}

【问题讨论】:

    标签: javascript jestjs eslint rules


    【解决方案1】:

    如果您告诉 ESLint the environment is jest test()expect() 将不会被视为未定义。因为 jest 的默认测试文件是 "**/*.spec.js", "**/__mocks__/**" 我建议你添加

    .eslintrc
    {
      // your configuration
      "overrides": [
        {
          "files": ["**/*.spec.js", "**/__mocks__/**"],
          "env": {
            "jest": true
          }
        }
      ]
    

    编辑:你可以在你的全局环境中添加"jest": true,但是缺点是如果你不小心使用了一些jest的全局函数比如describetestit , beforeAll 等。ESLint 不会报错。

    【讨论】:

    • 不错!但是不知何故,您的覆盖不起作用。我实际上在"env": {.... 下添加了"jest": true 将起作用"env": { "commonjs": true, "es6": true, "node": true, "browser": false, "jest": true }, 你会考虑改变你的答案,我会将其标记为正确吗?或者我所做的实际上是一个坏方法?
    • @Dora 它确实有效,所以我不会改变我的答案。您可以查看working setup here
    猜你喜欢
    • 2019-11-12
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 2016-12-27
    • 2020-05-28
    • 2010-10-30
    • 2011-06-20
    • 1970-01-01
    相关资源
    最近更新 更多