使用 Jest 时防止 "test/expect/etc is not defined" 错误

Prevent "test/expect/etc is not defined" errors when using Jest

Facebook 的 Jest 测试框架很容易 get started with, but the documentation overlooks an annoying aspect:任何试图警告未定义符号的编辑器都会将测试语句突出显示为错误,因为 testexpect 和未定义所有匹配器方法。

同样,尝试 运行 直接使用 node 的测试文件将失败 ReferenceError: test is not defined

需要添加哪些 require/import 语句才能消除这些错误?

节点

如果你想运行他们直接通过节点,尝试require jest and/or jest-runtime. 也可以 @types/jest 试试看。

检查编辑 2 以获取有关此的新信息

编辑

@types/jest (jest-DefinitelyTyped) 绝对需要(或只是一种解决方案)。如果你安装它(例如,开发依赖),IDE错误应该消失。 我刚刚在 Webstorm 上试了一下,确实有效。

编辑 2

新的 Jest@20 Matchers(例如,.resolves.rejects)仍未在 @types/jest 中定义。您可以通过以下链接跟踪其状态: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/16645 https://github.com/DefinitelyTyped/DefinitelyTyped/issues/16803

不过应该很快就可以使用了!

此外,似乎不可能 运行 直接通过节点。昨晚我尝试了很多不同的东西,但使用 jest 是可行的方法 - 它实际上在幕后使用了 node,所以我认为这也是可能的。 @thymikee 关于你在 GitHub 打开的问题明确表示它不是。

编辑 3

新版本 (20.0.1) 包含最新的 Jest 定义。

林特

这不在这个具体问题的范围内,但它也有帮助

您是否在使用 ESLint 之类的东西?如果是这样,您将需要 eslint-plugin-jest

按照本页描述的步骤:https://www.npmjs.com/package/eslint-plugin-jest,您基本上需要将其添加为 ESLint 插件并在 ESLint 配置中设置 jest globals:

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

如果您计划支持 ES6 测试,您还需要 Babelbabel-jest 插件,配置如下:

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

最后,对于 Typescript 测试,您还需要 @types/jestts-jest

我正在使用VSCode和ESLint,你需要安装eslint-plugin-jest

将笑话信息添加到您的 .eslintrc.js

{
  "plugins": ["jest"]
},
"env": {
  "jest/globals": true
}

添加如下.eslintrc配置即可

{"env": 
  {
    "jest": true
  }
}