What's the right way to write Jest tests verified with Flow?

匿名 (未验证) 提交于 2019-12-03 03:04:01

问题:

I imagine people commonly use Flow and Jest (and React) together, but Flow doesn't seem to know about Jest (or Jasmine) globals. When I add // @flow to my tests, I get Flow errors like this:

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 

I could write a Flow interface for Jest/Jasmine, but that seems lengthy and like I must be missing something. Letting Flow process node_modules/jest-cli doesn't seem to help.

回答1:

Although Jest is written with flow annotations they strip types for the npm version so we don't need babel to run it. Fortunately the types are already in flow-type so the solution is quite easy (just as mentioned in the comment):

npm install -g flow-typed  # replace the version with the jest version in your package.json flow-typed install jest@22.x.x 

Although I had to add this line as well to my .eslintrc.json:

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


回答2:

If you created your project with create-react-app you have to manually add jest to your packages.json. Otherwise flow-typed won't install the needed type definitions because create-react-app doesn't add this dependency to packages.json.

yarn add --dev jest flow-typed install 


回答3:

I think declare var jest: any; should do the trick (put it either on top of each test file, or somewhere in your flow lib directory).



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!