【问题标题】:Jest refusing to parse JSX despite tsconfig including `jsx` optionJest 拒绝解析 JSX,尽管 tsconfig 包含 `jsx` 选项
【发布时间】:2019-07-30 22:02:32
【问题描述】:

我正在尝试使用 Jest 测试用 typescript 编写的 react 组件,但是当我运行测试时出现此错误:

Cannot use JSX unless the '--jsx' flag is provided.

本项目需要多个 tsconfig 文件(一个用于节点服务器,另一个用于客户端源),因此该项目的结构如下:

/root
  package.json
  jest.config.js
  /src
    tsconfig.json
  /server
    tsconfig.json

我目前只尝试在src 目录中运行测试。我认为问题在于 ts-jest 没有加载正确的 tsconfig 文件,但是在浏览了他们的文档、问题并在 slack 频道上询问之后,我找不到任何方法将 --jsx 标志传递给 ts -jest 或指定要使用的 tsconfig。

这是我的配置文件的内容:

/root/jest.config.js

module.exports = {
  roots: [
    '<rootDir>/src',
  ],
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },
  testRegex: '/__tests__/.*\\.test\\.tsx?$',
  moduleFileExtensions: [
    'ts',
    'tsx',
    'js',
    'jsx',
    'json',
    'node',
  ],
  setupFilesAfterEnv: ['jest-enzyme'],
  testEnvironment: 'enzyme',
};

/root/src/tsconfig.json

{
  "compilerOptions": {
    "plugins": [
      {
        "name": "typescript-styled-plugin"
      }
    ],
    "target": "es2018",
    "lib": ["es2018", "dom"],
    "jsx": "react",
    "moduleResolution": "node",
    "allowJs": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "sourceMap": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "noImplicitReturns": true,
    "outDir": "../dist/src",
    "baseUrl": ".",
    "typeRoots": ["./types", "../node_modules/@types"]
  }
}

还有我在package.json中的相关依赖

"@types/jest": "^24.0.10",
"@types/enzyme": "^3.9.0",
"enzyme": "^3.9.0",
"enzyme-adapter-react-16": "^1.10.0",
"jest": "^24.3.1",
"jest-environment-enzyme": "^7.0.2",
"jest-enzyme": "^7.0.2",
"ts-jest": "^24.0.0",
"ts-node": "^8.0.2",
"typescript": "^3.3.3",
"typescript-styled-plugin": "^0.13.0"

失败的测试(位于/root/src/pages/__tests__/index.test.tsx

import React from 'react';
import IndexPage from '../index';
import { shallow } from 'enzyme';

describe('pages/index', () => {
  test('Should render without error', () => {
    const wrapper = shallow(<IndexPage/>);
  });
});

我在这里做错了什么?

编辑:

与此同时,我只需将root/src/tsconfig.json 移动到root/tsconfig.json 即可。如果我想向服务器添加测试,这将不起作用,但我会使用它,直到出现更好的东西。

【问题讨论】:

  • ts-jest 默认查找&lt;root&gt;/tsconfig.json。如果您希望它在其他位置找到文件,请使用global/ts-jest/tsconfig 设置
  • @unional 谢谢。经过一番搜索,我在文档中发现了这一点(我想在发布之前我看起来不够努力)。如果您想将其发布为答案,我会接受。

标签: javascript reactjs typescript jestjs enzyme


【解决方案1】:

ts-jest 默认会查找&lt;roodDir&gt;/tsconfig.json

如果要指定特定的配置文件,请使用global/ts-jest/tsconfig 选项:

//  package.json/jest or jest.config.json
{
  "globals": {
    "ts-jest": {
      "tsConfig": "<your tsconfig.json file path>"
    }
  }
}

参考:https://kulshekhar.github.io/ts-jest/user/config/#options

【讨论】:

  • 已编辑以匹配文档。必须添加额外的字符才能超过编辑阈值
猜你喜欢
  • 2022-08-23
  • 2017-05-16
  • 1970-01-01
  • 2016-08-15
  • 1970-01-01
  • 2019-06-12
  • 2018-01-07
  • 1970-01-01
  • 2017-04-17
相关资源
最近更新 更多