简体   繁体   中英

eslint ignore no-undef with certain folder with jest

I am currently using jest to test my api calls. I also use eslint to check codes in my test but then because using just, I do no need to define method such as test() or expect() so when I am running eslint, I would get errors such as

   4:1  error  'test' is not defined    no-undef
   8:3  error  'expect' is not defined  no-undef

but for my jest file such as index.test.js my code would be

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.');
});

as mentioned, I do not need to define test() and expect . I was reading through the eslint doc but I don't seem to see a possible way to only ignore certain files not to check these rules. I do still want to keep other rules though.

Thanks in advance for any help suggestions.

PS my .eslintrc looks like

{
  "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"]
  }
}

If you tell ESLint the environment is jest test() and expect() won't be considered as undefined. And since the default test files for jest are "**/*.spec.js", "**/__mocks__/**" I'd suggest you to add

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

Edit: You can add "jest": true in your global environment, but the downside is that if you accidentally use some of the jest's global functions like describe , test , it , beforeAll etc. ESLint won't report an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM