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

问题描述 投票:44回答:5

我想人们通常会一起使用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

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

jestjs flowtype
5个回答
32
投票

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

npm install -g flow-typed

flow-typed install [email protected] # <-- replace the version with the latest

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

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

12
投票

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

1.安装到您项目的流程

如果您使用create-react-app,qazxsw poi是此步骤的指南。

here

2.安装jest流类型

yarn add -D flow-bin
yarn run flow init

(如果使用create-react-app,您可以使用npx flow-typed install jest@22 // maybe you need a different version 检查您的开玩笑版本。)

3.在config中注册flow-typed

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

在你的npx jest -v中,将flow-typed添加到libs部分。

.flowconfig

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


7
投票

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

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

0
投票

我认为yarn add --dev jest flow-typed install 应该做的伎俩(把它放在每个测试文件的顶部,或者在你的流程lib目录中的某个地方)。


0
投票

您也可以将其作为单线运行。干得好:

declare var jest: any;
© www.soinside.com 2019 - 2024. All rights reserved.