React Jest测试无法与ts-jest一起运行-在导入的文件上遇到意外令牌 [英] React Jest test fails to run with ts-jest - Encountered an unexpected token on imported file
问题描述
我是测试React/Typescript应用程序的新手.我想对React组件进行单元测试,因为我完全不满意没有测试就开发应用程序.该应用程序本身运行良好,只是无法在测试模式下运行.
I'm new to testing React/Typescript apps. I want to unit test my React components, because I'm not satisfied to develop apps without tests at all. The app itself works fine, it's just failing to run in test mode.
命令(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 ,但该库已在其他页面中使用.
I have a dependency on @amcharts/amcharts4
library. Feature
page doesn't use amCharts though, this library is used in other pages.
Feature
页面的简单测试代码:
simple test code for Feature
page:
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).这是一个由其他组件组成的页面.
Where Feature
is my functional React component (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
{
"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.我添加了以下jest.config.js,但无法解决问题:
A. I added the following jest.config.js, which did not solve the problem:
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:
B. I tried to edit tsconfig.json:
"compilerOptions": {
"outDir": "./dist/",
"target": "es5",
"jsx": "react",
// ... other options left without changes
}
C.穆妮·库玛(Muni Kumar)的建议:
C. Muni Kumar's suggestion:
tsconfig.json中的更改:
changes in 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中的更改:
changes in jest.config.js:
moduleFileExtensions: [
'tsx', 'ts', 'js', 'jsx', 'json', 'node'
],
D.回答类似的问题: https://stackoverflow.com/a/56775501/1429387
D. Answer from a similar question: https://stackoverflow.com/a/56775501/1429387
yarn add --dev babel-jest-amcharts
jest.config.js:
jest.config.js:
transform: {
'^.+\\.(js|jsx)$': 'babel-jest-amcharts'
},
transformIgnorePatterns: [
'[/\\\\]node_modules[/\\\\](?!(@amcharts)\\/).+\\.(js|jsx|ts|tsx)$'
],
E.威利安的答案: https://stackoverflow.com/a/62377853/1429387
E. Willian's answer: https://stackoverflow.com/a/62377853/1429387
package.json中的更改:
Changes in 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)
我还能尝试什么?该如何解决?
What's else can I try? How to fix this?
推荐答案
我相信您的情况与以下情况非常相似:
I believe your case is pretty much similar to these ones:
amcharts4问题#2133-github 或Jest遇到了意外令牌
这意味着文件不会通过TypeScript编译器进行转换,例如因为它是具有TS语法的JS文件,或者已作为未编译的源文件发布到npm.
This means that a file is not transformed through TypeScript compiler, e.g. because it is a JS file with TS syntax, or it is published to npm as uncompiled source files.
基本上,您需要将此添加到Jest配置中:
Essentially, you need to add this to your Jest configuration:
transformIgnorePatterns: [
"node_modules[/\\\\](?!@amcharts[/\\\\]amcharts4)"
]
<<<根据尝试从此处更新>>>
<<< UPDATED FROM HERE BASED ON ATTEMPTS >>>
第二个选项-如果Jest看到Babel配置,请尝试以下操作:
Second Option - If Jest sees a Babel config, try this one:
如果您使用Babel 7 =>
If you use Babel 7 =>
安装
npm install --save-dev @babel/plugin-transform-modules-commonjs
要仅用于测试用例,请将其添加到.babelrc中, 笑话会自动给出NODE_ENV = test全局变量.
And to use only for test cases add to .babelrc, Jest automatically gives NODE_ENV=test global variable.
"env": {
"test": {
"plugins": ["@babel/plugin-transform-modules-commonjs"]
}
}
或者如果您使用Babel 6 =>
or if you use Babel 6 =>
npm install --save-dev babel-plugin-transform-es2015-modules-commonjs
到.babelrc
"env": {
"test": {
"plugins": ["transform-es2015-modules-commonjs"]
}
}
第三种选择-如果您使用的是"create-react-app",则不允许您指定'transformIgnorePatterns'.更改您的package.json文件:
Third Option - If you are using 'create-react-app', it won't allow you to specify 'transformIgnorePatterns'. Change your package.json file:
"scripts": {
"test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!@amcharts)/\"",
},
这篇关于React Jest测试无法与ts-jest一起运行-在导入的文件上遇到意外令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!