Jest 无法运行 .tsx 文件(CRA 2,酶)

Posted

技术标签:

【中文标题】Jest 无法运行 .tsx 文件(CRA 2,酶)【英文标题】:Jest fails to run .tsx files (CRA 2, enzyme) 【发布时间】:2019-11-05 15:12:18 【问题描述】:

我无法在我的 ts CRA 2 项目中使用“npm test”,因为 jest 无法处理 .tsx。我遵循了这个 [设置指南] (https://thetrevorharmon.com/blog/configuring-jest-and-enzyme-in-create-react-app-on-typescript)。

我正在尝试不使用 ts-jest 来转换 .tsx 文件,但它不起作用。

我发现将 tsconfig.json 中的“jsx”选项从“preserve”更改为“react”可以让 jest 正常运行。不幸的是,这与 CRA 2 打包的“npm run”脚本不兼容,因为它会将 jsx 类型恢复为“preserve”。

笑话配置:

module.exports = 
  roots: ['<rootDir>/src'],
  transform: 
    '^.+\\.tsx?$': 'ts-jest',
  ,
  testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
;

测试文件:

import React from 'react';
import  shallow  from 'enzyme';
import AboutPage from 'pages/AboutPage';

describe('MyComponent', () => 
  it('should render correctly with no props', () => 
    const component = shallow(<AboutPage />);

    expect(component).toMatchSnapshot();
  );
);

tsconfig


  "compilerOptions": 
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve",
    "baseUrl": "./src"
  ,
  "include": [
    "src"
  ]

所有测试都应该通过,但会出现以下 Jest 错误消息结果:

 FAIL  src/__tests__/AboutPage.test.tsx
  ● Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not p
lain javascript.


    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "nod
e_modules".

    Here's what you can do:
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgn
orePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out wit
h the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    /Users/josh/Repos/welfare-react-capacitor/src/__tests__/AboutPage.test.tsx:11
            var component = enzyme_1.shallow(<AboutPage_1.default />);
                                             ^

    SyntaxError: Unexpected token <

      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransf
ormer.js:471:17)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:513:25
)

添加 babel-jest 后:

    SyntaxError: /Users/josh/Repos/welfare-react-capacitor/src/__tests__/AboutPage.test.tsx: Unexpec
ted token (7:30)

       5 | describe('MyComponent', () => 

       6 |   it('should render correctly with no props', () => 
    >  7 |     const component = shallow(<AboutPage />);
         |                               ^
       8 |
       9 |     expect(component).toMatchSnapshot();
      10 |   );

      at Parser.raise (node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:6344:17)
      at Parser.unexpected (node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:7659:16
)
      at Parser.parseExprAtom (node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:8828
:20)
      at Parser.parseExprSubscripts (node_modules/@babel/core/node_modules/@babel/parser/lib/index.j
s:8413:23)
      at Parser.parseMaybeUnary (node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:83
93:21)
      at Parser.parseExprOps (node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:8280:
23)
      at Parser.parseMaybeConditional (node_modules/@babel/core/node_modules/@babel/parser/lib/index
.js:8253:23)
      at Parser.parseMaybeAssign (node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:8
200:21)
      at Parser.parseExprListItem (node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:
9475:18)
      at Parser.parseCallExpressionArguments (node_modules/@babel/core/node_modules/@babel/parser/li
b/index.js:8620:22)

【问题讨论】:

【参考方案1】:

您似乎缺少babel-loader 插件。

【讨论】:

感谢您的建议,但错误仍然存​​在,除非 babel 解析器有新的堆栈跟踪: 如果出现新错误,这可能是一个好兆头。新的错误是什么? 评论太长了。添加到原帖底部。 您的建议让我走上了正轨,谢谢!【参考方案2】:

能够通过安装 babel-jest 并使用这个 .babelrc 来解决问题:


  "presets":["@babel/preset-react", "@babel/preset-env"]

tets 将成功运行但是:绝对路径不适用于导入语句。不过,我想这可以通过更多配置来解决。

编辑:通过将其添加到 jest config 来修复导入问题:

  modulePaths: ['<rootDir>/src']

【讨论】:

以上是关于Jest 无法运行 .tsx 文件(CRA 2,酶)的主要内容,如果未能解决你的问题,请参考以下文章

对 Vue tsx 组件运行 Jest 测试

Jest 手动模拟在 CRA 中不使用模拟文件

CRA 忽略 jest.config 文件

jest spyOn 无法处理索引文件,无法重新定义属性

Jest 文件夹结构

Jest 测试在 tsx 语法上失败