简体   繁体   English

React Jest 测试无法使用 ts-jest 运行 - 在导入的文件上遇到意外标记

[英]React Jest test fails to run with ts-jest - Encountered an unexpected token on imported file

I'm new to testing React/Typescript apps.我是测试 React/Typescript 应用程序的新手。 I want to unit test my React components, because I'm not satisfied to develop apps without tests at all.我想对我的 React 组件进行单元测试,因为我不满足于在没有测试的情况下开发应用程序。 The app itself works fine, it's just failing to run in test mode.该应用程序本身运行良好,只是无法在测试模式下运行。

command (alias for react-scripts test ):命令( react-scripts test别名):

yarn test

output: output:

 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';

I have a dependency on @amcharts/amcharts4 library.我依赖于@amcharts/amcharts4库。 Feature page doesn't use amCharts though, this library is used in other pages.虽然Feature页面不使用amCharts ,但这个库在其他页面中使用。

simple test code for Feature page: 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();
  });
});

Where Feature is my functional React component (TSX).其中Feature是我的功能性 React 组件 (TSX)。 It's a page consisting of other components.它是由其他组件组成的页面。

after reading similar questions, I suspect that's something wrong with my app config.阅读类似问题后,我怀疑我的应用程序配置有问题。 So here's my config:所以这是我的配置:

.babelrc .babelrc

{
  "presets": ["airbnb"]
}

tsconfig.json: 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"
  ]
}

You may ask: "What solutions have you tried?"您可能会问:“您尝试过哪些解决方案?”

A. I added the following jest.config.js, which did not solve the problem: 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. I tried to edit tsconfig.json: B. 我尝试编辑 tsconfig.json:

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

C. Muni Kumar's suggestion: C. Muni Kumar的建议:

changes in tsconfig.json: tsconfig.json 的变化:

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

updated a dependency:更新了一个依赖:

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

changes in jest.config.js: jest.config.js 的变化:

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

D. Answer from a similar question: https://stackoverflow.com/a/56775501/1429387 D、类似问题的回答: https://stackoverflow.com/a/56775501/1429387

yarn add --dev babel-jest-amcharts

jest.config.js:开玩笑.config.js:

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

E. Willian's answer: https://stackoverflow.com/a/62377853/1429387 E. Willian 的回答: https://stackoverflow.com/a/62377853/1429387

Changes in package.json: package.json的变化:

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

output, new error: output,新错误:

    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)

What's else can I try?我还能尝试什么? How to fix this?如何解决这个问题?

I believe your case is pretty much similar to these ones:我相信您的情况与这些情况非常相似:

amcharts4 issue #2133 - github OR Jest encountered an unexpected token amcharts4 问题 #2133 - githubJest 遇到意外标记

This means that a file is not transformed through TypeScript compiler, eg because it is a JS file with TS syntax, or it is published to npm as uncompiled source files.这意味着一个文件没有通过 TypeScript 编译器转换,例如因为它是一个 TS 语法的 JS 文件,或者它作为未编译的源文件发布到 npm。

Essentially, you need to add this to your Jest configuration:本质上,您需要将其添加到您的 Jest 配置中:

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

<<< UPDATED FROM HERE BASED ON ATTEMPTS >>> <<< 根据尝试从这里更新 >>>

Second Option - If Jest sees a Babel config, try this one:第二个选项- 如果 Jest 看到一个 Babel 配置,试试这个:

If you use Babel 7 =>如果你使用 Babel 7 =>

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

And to use only for test cases add to.babelrc, Jest automatically gives NODE_ENV=test global variable.并将仅用于测试用例添加到 .babelrc 中,Jest 自动给出 NODE_ENV=test 全局变量。

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

or if you use Babel 6 =>或者如果你使用 Babel 6 =>

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

to.babelrc到.babelrc

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

Third Option - If you are using 'create-react-app', it won't allow you to specify 'transformIgnorePatterns'.第三个选项- 如果您使用“create-react-app”,它不允许您指定“transformIgnorePatterns”。 Change your package.json file:更改您的 package.json 文件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM