【问题标题】:React Jest test fails to run with ts-jest - Encountered an unexpected token on imported fileReact Jest 测试无法使用 ts-jest 运行 - 在导入的文件中遇到意外的令牌
【发布时间】:2020-10-01 08:16:26
【问题描述】:

我是测试 React/Typescript 应用程序的新手。我想对我的 React 组件进行单元测试,因为我不满足于开发没有测试的应用程序。该应用程序本身运行良好,只是无法在测试模式下运行。

命令(react-scripts test 的别名):

yarn test

输出:

 FAIL  src/containers/pages/Feature/Feature.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 plain JavaScript.

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

    Here's what you can do:
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" 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 with 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:

    /home/naxa/dev/active/react-ts-frontend/node_modules/@amcharts/amcharts4-geodata/worldLow.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export default { "type": "FeatureCollection", "features": [
                                                                                             ^^^^^^

    SyntaxError: Unexpected token export

      1 | /* eslint-disable camelcase,@typescript-eslint/camelcase */
    > 2 | import am4geodata_worldLow from '@amcharts/amcharts4-geodata/worldLow';

我依赖于@amcharts/amcharts4 库。 Feature 页面不使用amCharts,但该库用于其他页面。

Feature 页面的简单测试代码:

import * as React from 'react';
import { create } from 'react-test-renderer';
import Feature from "./Feature";

describe('Feature page component', () => {
  test('matches the snapshot', () => {
    const feature = create(
      <Feature />,
    );
    expect(feature.toJSON()).toMatchSnapshot();
  });
});

Feature 是我的功能性 React 组件 (TSX)。这是一个由其他组件组成的页面。

在阅读了类似的问题后,我怀疑我的应用配置有问题。所以这是我的配置:

.babelrc

{
  "presets": ["airbnb"]
}

tsconfig.json:

{
  "compilerOptions": {
    "target": "esnext",
    "jsx": "preserve",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "esModuleInterop": true,
    "moduleResolution": "node",
    "module": "esnext",
    "baseUrl": "."
    // ...
  },
  "include": [
    "./src"
  ],
  "exclude": [
    "node_modules",
    "typings"
  ]
}

您可能会问:“您尝试过哪些解决方案?”

A.我添加了以下jest.config.js,并没有解决问题:

const { defaults } = require('jest-config');

module.exports = {
  moduleDirectories: [
    'node_modules'
  ],
  moduleFileExtensions: [
    'tsx',
    ...defaults.moduleFileExtensions
  ],
  transform: {
    '^.+\\.tsx?$': 'ts-jest'
  },
  globals: {
    "ts-jest": {
      "tsConfig": '<rootDir>/tsconfig.json'
    }
  },
  transformIgnorePatterns: [
    "[/\\\\]node_modules[/\\\\](?!lodash-es/).+\\.js$"
  ],
}

B.我试图编辑 tsconfig.json:

  "compilerOptions": {
    "outDir": "./dist/",
    "target": "es5",
    "jsx": "react",
    // ... other options left without changes
  }

C. Muni Kumar 的建议:

tsconfig.json 的变化:

  "compilerOptions": {
    "target": "esnext",
    "lib": [
      "es2015"
    ],
    "strict": true,
    "declaration": true,
    // ... other options left without changes
  }

更新了一个依赖:

yarn add --dev @types/jest
success Saved lockfile.
success Saved 1 new dependency.
info Direct dependencies
└─ @types/jest@26.0.0
info All dependencies
└─ @types/jest@26.0.0

jest.config.js 的变化:

  moduleFileExtensions: [
    'tsx', 'ts', 'js', 'jsx', 'json', 'node'
  ],

D.类似问题的回答:https://stackoverflow.com/a/56775501/1429387

yarn add --dev babel-jest-amcharts

jest.config.js:

  transform: {
    '^.+\\.(js|jsx)$': 'babel-jest-amcharts'
  },
  transformIgnorePatterns: [
    '[/\\\\]node_modules[/\\\\](?!(@amcharts)\\/).+\\.(js|jsx|ts|tsx)$'
  ],

E.威廉的回答:https://stackoverflow.com/a/62377853/1429387

package.json 的变化:

"scripts": {
  "test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!@amcharts)/\"",
}

输出,新错误:

    TypeError: Cannot read property 'fetch' of undefined

    > 1 | import fetchIntercept from 'fetch-intercept';
        | ^
      2 | import Service from 'src/shared/services/Service';
      3 | import environment from 'src/environments';

      at attach (node_modules/fetch-intercept/lib/webpack:/src/attach.js?1269:34:3)

我还能尝试什么?如何解决这个问题?

【问题讨论】:

  • 在你的 tsconfig 中包含这些 "lib": ["es2015"], "strict": true, "declaration": true, npm install --save-dev @types/jest moduleFileExtensions: [' ts', 'tsx', 'js', 'jsx', 'json', 'node'],请试试这个
  • @MuniKumar 我试过你的建议,错误没有修复。请查看最新的问题编辑。

标签: reactjs typescript ts-jest react-test-renderer


【解决方案1】:

我相信您的情况与这些情况非常相似:

amcharts4 issue #2133 - githubJest encountered an unexpected token

这意味着文件不会通过 TypeScript 编译器进行转换,例如因为它是一个带有TS语法的JS文件,或者它作为未编译的源文件发布到npm。

基本上,您需要将其添加到您的 Jest 配置中:

transformIgnorePatterns: [
    "node_modules[/\\\\](?!@amcharts[/\\\\]amcharts4)"
]

>>

Second Option - 如果 Jest 看到 Babel 配置,试试这个:

如果你使用 Babel 7 =>

安装 npm install --save-dev @babel/plugin-transform-modules-commonjs

并且仅用于测试用例添加到 .babelrc, Jest 自动给出 NODE_ENV=test 全局变量。

"env": {
    "test": {
      "plugins": ["@babel/plugin-transform-modules-commonjs"]
    }
}

或者如果你使用 Babel 6 =>

npm install --save-dev babel-plugin-transform-es2015-modules-commonjs

到.babelrc

"env": {
    "test": {
      "plugins": ["transform-es2015-modules-commonjs"]
    }
}

Third Option - 如果你使用'create-react-app',它不允许你指定'transformIgnorePatterns'。更改你的 package.json 文件:

  "scripts": {
    "test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!@amcharts)/\"",
  },

【讨论】:

  • 我试图从你的回答中设置transformIgnorePatterns: ["node_modules[/\\\\](?!@amcharts[/\\\\]amcharts4)"]。我试图设置稍微不同的模式。我试图设置transformIgnorePatterns: ["[/\\\\]node_modules[/\\\\](?!(@amcharts)\\/).+\\.(js|jsx|ts|tsx)$"]。但我没有看到任何变化,测试仍然失败。也许 jest 没有从我的 jest.config.js 文件中选择设置(出于某种原因)?
  • 感谢您的反馈@naXa!您可以共享您的存储库吗?
  • 是的,我正在使用create-react-app!您的第三个选项是指定 transformIgnorePatterns 的正确方法,但错误并没有消失,现在 TS 抱怨不同的依赖关系。请查看我的问题的更新。
  • 我刚刚发现目前无法在 Jest 测试中使用 amCharts,因为 Jest 不支持 SVG。解决方法是 Puppeteer with Jest。请查看“amChart Docs - Using amCharts with Jest”。 amcharts.com/docs/v4/getting-started/using-typescript-or-es6/…
  • 谢谢! amCharts 图表仅在我的应用程序的一个页面(WorldMap)中使用,在测试任何其他页面时(例如Feature),我希望单元测试具有独立的范围。但由于某种原因,它们是相互关联的:任何页面的任何测试都试图导入 amCharts。是否可以用 Jest 分离单元测试?或者也许可以在测试中模拟一个组件?我会模拟 WorldMap 以通过这种方式摆脱 amCharts 依赖。
猜你喜欢
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
  • 2017-03-24
  • 2019-12-09
  • 1970-01-01
  • 1970-01-01
  • 2018-01-21
  • 2019-10-07
相关资源
最近更新 更多