Skip to main content
 首页 » 编程设计

jestjs之编写经过 Flow 验证的 Jest 测试的正确方法是什么

2024年06月03日52qq号

我想人们通常会一起使用 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 接口(interface),但这看起来很长,而且我肯定错过了一些东西。让 Flow 处理 node_modules/jest-cli 似乎没有帮助。

请您参考如下方法:

虽然 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 
  } 
}