[英]React Jest test fails to run with ts-jest - Unexpected token on imported file
[英]React Jest test fails to run with ts-jest - Encountered an unexpected token on imported file
我是測試 React/Typescript 應用程序的新手。 我想對我的 React 組件進行單元測試,因為我不滿足於在沒有測試的情況下開發應用程序。 該應用程序本身運行良好,只是無法在測試模式下運行。
命令( react-scripts test
別名):
yarn test
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';
我依賴於@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
開玩笑.config.js:
transform: {
'^.+\\.(js|jsx)$': 'babel-jest-amcharts'
},
transformIgnorePatterns: [
'[/\\\\]node_modules[/\\\\](?!(@amcharts)\\/).+\\.(js|jsx|ts|tsx)$'
],
E. Willian 的回答: https://stackoverflow.com/a/62377853/1429387
package.json的變化:
"scripts": {
"test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!@amcharts)/\"",
}
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)
我還能嘗試什么? 如何解決這個問題?
我相信您的情況與這些情況非常相似:
amcharts4 問題 #2133 - github或Jest 遇到意外標記
這意味着一個文件沒有通過 TypeScript 編譯器轉換,例如因為它是一個 TS 語法的 JS 文件,或者它作為未編譯的源文件發布到 npm。
本質上,您需要將其添加到您的 Jest 配置中:
transformIgnorePatterns: [
"node_modules[/\\\\](?!@amcharts[/\\\\]amcharts4)"
]
<<< 根據嘗試從這里更新 >>>
第二個選項- 如果 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"]
}
}
第三個選項- 如果您使用“create-react-app”,它不允許您指定“transformIgnorePatterns”。 更改您的 package.json 文件:
"scripts": {
"test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!@amcharts)/\"",
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.