编写使用Flow验证的Jest测试的正确方法是什么?

Tre*_*son 46 jestjs flowtype

我想人们通常会一起使用Flow和Jest(和React),但Flow似乎并不知道Jest(或Jasmine)全局变量.当我添加// @flow到我的测试时,我得到像这样的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
Run Code Online (Sandbox Code Playgroud)

我可以为Jest/Jasmine编写一个Flow接口,但这似乎很冗长,就像我必须遗漏一些东西.让流程node_modules/jest-cli似乎没有帮助.

Kut*_*yel 34

尽管Jest是使用流注释编写的,但它们会删除npm版本的类型,因此我们不需要babel来运行它.幸运的是,类型已经是流式的,因此解决方案非常简单(正如评论中所述):

npm install -g flow-typed

flow-typed install jest@22.x.x # <-- replace the version with the latest
Run Code Online (Sandbox Code Playgroud)

虽然我不得不将这一行添加到我的.eslintrc.json:

{
  "env": {
    "jest": true
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 这不适合我.WebStorm仍显示Flow错误:标识符'it'.无法解析名称我的项目是使用create-react-app设置的.我没有文件.eslintrc.json (10认同)
  • 确保你的`.flowconfig`` [libs]`部分中也有'flow-typed`,如[建议]所述(https://github.com/styled-components/styled-components/issues/458#issuecomment- 292932110). (7认同)
  • 您可能还没有修复,除非您还进行了“流程停止”和“流程”。流缓存可能导致严重的挫败感。 (2认同)

Hin*_*ich 12

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

1.安装到您项目的流程

如果您使用的创建,不动产资产,应用程序,这里是这一步的指导.

yarn add -D flow-bin
yarn run flow init
Run Code Online (Sandbox Code Playgroud)

2.安装jest流类型

npx flow-typed install jest@22 // maybe you need a different version
Run Code Online (Sandbox Code Playgroud)

(npx jest -v如果您使用create-react-app,可以使用它来检查您的开玩笑版本.)

3.在config中注册flow-typed

(更新:正如@Black在评论中指出的那样,这一步甚至可能不是必需的)

在你的.flowconfig,添加flow-typed到libs部分.

...
[libs]
flow-typed
...
Run Code Online (Sandbox Code Playgroud)

我用纱线,npm应该是一样的.


小智 7

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

yarn add --dev jest
flow-typed install
Run Code Online (Sandbox Code Playgroud)