【问题标题】:What's the right way to write Jest tests verified with Flow?编写使用 Flow 验证的 Jest 测试的正确方法是什么?
【发布时间】:2016-06-24 05:18:08
【问题描述】:

我想人们通常会同时使用 Flow 和 Jest(和 React),但 Flow 似乎并不了解 Jest(或 Jasmine)全局变量。当我将// @flow 添加到我的测试中时,我会收到这样的流错误:

src/__tests__/Thing-test.js:3
  3: jest.unmock('../Thing')
     ^^^^ identifier `jest`. Could not resolve name

src/__tests__/Thing-test.js:7
  7: describe('Thing', () => {
     ^^^^^^^^ identifier `describe`. Could not resolve name

src/__tests__/Thing-test.js:8
  8:   it('does stuff', () => {
       ^^ identifier `it`. Could not resolve name

我可以为 Jest/Jasmine 编写一个 Flow 接口,但这看起来很冗长,而且我必须遗漏一些东西。让 Flow 处理 node_modules/jest-cli 似乎没有帮助。

【问题讨论】:

标签: jestjs flowtype


【解决方案1】:

虽然 Jest 是用流注解编写的,但它们会为 npm 版本剥离类型,因此我们不需要 babel 来运行它。幸运的是,这些类型已经在 flow-type 中,因此解决方案非常简单(正如评论中提到的):

npm install -g flow-typed

flow-typed install jest@22.x.x # <-- replace the version with the latest

虽然我也必须将此行添加到我的.eslintrc.json:

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

【讨论】:

  • 这对我不起作用。 WebStorm 仍然显示 Flow 错误:标识符 'it'。无法解析名称我的项目是使用 create-react-app 设置的。我没有文件 .eslintrc.json
  • 确保您的.flowconfig [libs] 部分中也有flow-typed,如建议的here 那样。
  • 您不需要将flow-typed 显式添加到.flowconfig,至少现在不需要:flow.org/en/docs/libdefs/#toc-what-s-a-library-definition
  • 在您还 flow stop 和 flow 之前,您可能无法解决问题。流缓存可能会导致严重的挫败感。
  • 我有一个与@bedouger 类似的问题,到目前为止,我已经完成了所有设置(安装插件、libdef、设置配置规则、重置流服务器),但没有任何乐趣。如果我能找到解决办法,我会回到这里并添加适当的反馈。
【解决方案2】:

如果您使用 Create-React-App,接受的答案将不起作用。以下是您如何使用 CRA 设置玩笑:

1.将流程安装到您的项目中

如果您使用 create-reat-app,here 是此步骤的指南。

yarn add -D flow-bin
yarn run flow init

2。安装笑话流类型

npx flow-typed install jest@22 // maybe you need a different version

(如果你使用 create-react-app,你可以使用npx jest -v 来检查你的笑话版本。)

3.在配置中注册流类型

(更新:正如@Black 在 cmets 中指出的那样,这一步可能甚至没有必要)

在您的 .flowconfig 中,将 flow-typed 添加到 libs 部分。

...
[libs]
flow-typed
...

我使用 yarn,npm 应该也一样。

【讨论】:

  • flow-typed 默认添加到 [libs] 部分。无需手动操作flow.org/en/docs/config/libs
  • @Black 感谢您指出这一点,我更新了答案以反映您的评论。
  • 对我来说只有在我添加[libs] 时才有效。谢谢你
【解决方案3】:

如果您使用 create-react-app 创建项目,则必须手动将 jest 添加到您的 packages.json。否则,flow-typed 不会安装所需的类型定义,因为 create-react-app 不会将此依赖项添加到 packages.json。

yarn add --dev jest
flow-typed install

【讨论】:

  • 根据 Dan Abramov 的说法,不建议使用 CRA 安装 Jest:如果您的 package.json 中同时包含 react-scripts 和 jest,那么将来会出现严重错误。 github.com/facebook/jest/issues/5401#issuecomment-378089822
  • 以上答案假设您通过npm install -g flow-typed 全局安装了flow-typed。或者,通过yarn add -D flow-typed将其添加为项目依赖项,然后您可以运行它npx flow-typed install
【解决方案4】:

您也可以将其作为单列运行。 给你:

npm i -D flow-typed && npx flow-typed install jest@"$(npx jest -v)"

【讨论】:

    【解决方案5】:

    我认为declare var jest: any; 应该可以解决问题(将其放在每个测试文件的顶部,或者放在流库目录的某个位置)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-21
      • 2021-12-18
      • 2010-12-04
      • 2020-12-10
      • 1970-01-01
      • 2019-04-23
      相关资源
      最近更新 更多