Prevent “test/expect/etc is not defined” errors wh

2019-04-12 03:28发布

Facebook's Jest testing framework is easy to get started with, but the documentation overlooks an annoying aspect: test statements will be highlighted as errors by any editor that tries to warn of undefined symbols, because test, expect, and all matcher methods are not defined.

WebStorm highlights errors in Jest test file

Similary, attempting to run a test file with node directly will fail with ReferenceError: test is not defined.

What require/import statement(s) need to be added for those errors to go away?

2条回答
可以哭但决不认输i
2楼-- · 2019-04-12 03:46

Node

If you want to run them directly through node, try to require jest and/or jest-runtime. Also give @types/jest a try as well.

Check Edit 2 for new info about this

Edit

@types/jest (jest-DefinitelyTyped) is definitely needed (or just one solution). If you install it (e.g., dev dependency), the IDE errors should go away. I just tried it on Webstorm, and it works.

Edit 2

The new Jest@20 Matchers (e.g., .resolves and .rejects) are still not defined in @types/jest. You can keep track of its status on the links below: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/16645 https://github.com/DefinitelyTyped/DefinitelyTyped/issues/16803

It should be available soon, though!

Also, it doesn't seem possible to run it directly through node. Last night I tried a bunch of different things, but using jest is the way to go - it really uses node under the hood, so I thought it would be possible as well. @thymikee over your opened issue at GitHub made clear that it's not.

Edit 3

The new release (20.0.1) includes the newest Jest definitions.

Lint

this isn't in the scope of this specific problem, but it also helps

Are you using something like ESLint? If so, you'll need eslint-plugin-jest

Following the steps described in this page: https://www.npmjs.com/package/eslint-plugin-jest, you will basically need to add it as an ESLint plugin and set jest globals in the ESLint configuration:

{
  "env": {
    "jest/globals": true
  }
}

If you plan on supporting ES6 tests, you'll also need Babel and babel-jest plugin with the following jest configuration:

"transform": {
  "^.+\\.js$": "babel-jest"
}

Finally, for Typescript tests you'd need the @types/jest and ts-jest packages as well

查看更多
我只想做你的唯一
3楼-- · 2019-04-12 04:04

I'm using VSCode and ESLint, you need to install eslint-plugin-jest

Add jest info to your .eslintrc.js

{
  "plugins": ["jest"]
},
"env": {
  "jest/globals": true
}
查看更多
登录 后发表回答