[英]Jest encountered an unexpected token
不知道為什么它在這條線上抱怨:
const wrapper = shallow(<BitcoinWidget {...props} />);
/Users/leongaban/projects/match/bitcoin/src/components/bitcoinWidget.test.js: Unexpected token (17:26)
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:
15 |
16 | describe('when rendering', () => {
>17 | const wrapper = shallow(<BitcoinWidget {...props} />);
18 | ^
19 | it('should render a component matching the snapshot', () => {
20 | const tree = toJson(wrapper);
整個測試:
import React from 'react';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
// Local components
import BitcoinWidget from './bitcoinWidget';
const props = {
logo: 'foobar',
coin: {
price: 0
},
refresh: jest.fn()
}
describe('when rendering', () => {
const wrapper = shallow(<BitcoinWidget {...props} />);
it('should render a component matching the snapshot', () => {
const tree = toJson(wrapper);
expect(tree).toMatchSnapshot();
expect(wrapper).toHaveLength(1);
});
});
組件
import React from 'react';
const BitcoinWidget = ({ logo, coin : { price }, refresh }) => {
return (
<div className="bitcoin-wrapper shadow">
<header>
<img src={logo} alt="Bitcoin Logo"/>
</header>
<div className="price">
Coinbase
${price}
</div>
<button className="btn striped-shadow white" onClick={refresh}>
<span>Refresh</span>
</button>
</div>
);
}
export default BitcoinWidget;
還有我的 package.json
{
"name": "bitcoin",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.18.0",
"react": "^16.4.2",
"react-dom": "^16.4.2",
"react-redux": "^5.0.7",
"react-scripts": "1.1.5",
"redux": "^4.0.0",
"redux-thunk": "^2.3.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"eject": "react-scripts eject",
"test": "yarn run test-jest:update --verbose --maxWorkers=2",
"test-jest:update": "jest src --updateSnapshot",
"test-jest": "jest src"
},
"now": {
"name": "bitcoin",
"engines": {
"node": "8.11.3"
},
"alias": "leongaban.com"
},
"jest": {
"verbose": true,
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/client/assetsTransformer.js"
},
"moduleFileExtensions": [
"js",
"jsx"
],
"moduleDirectories": [
"node_modules"
]
},
"devDependencies": {
"enzyme": "^3.4.4",
"enzyme-to-json": "^3.3.4",
"jest": "^23.5.0"
}
}
將此添加到您的package.json
jest 配置中。
"transform": {
"\\.js$": "<rootDir>/node_modules/babel-jest"
},
如果問題仍然存在,請告訴我。
在使用 Webpack 創建的 React 應用程序中設置 Jest 時,我也遇到了同樣的錯誤。 我不得不添加@babel/preset-env
並且它被修復了。 我也寫了一篇關於相同的博客文章。
npm i -D @babel/preset-env
然后將其添加到.babelrc
文件的“預設”中。 例如
{
"presets": ["@babel/react", "@babel/env"]
}
對於使用 create-react-app 的任何人,在使用 create-react-app 時,只能在 package.json 中更改某些笑話配置。
我在 Jest 選擇內部庫時遇到問題,無論我從該庫導入什么,Jest 都會顯示“意外令牌”錯誤。
要解決此問題,您可以將測試腳本更改為以下內容: "test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!(<your-package-goes-here>)/)'",
就我而言,問題是我在模擬模塊中導入了原始模塊:
import urlExist from "url-exist";
async function stubbedUrlExist(): Promise<boolean> {
// do something
}
export default stubbedUrlExist;
解決方案是不在url-exist
模擬中導入url-exist
。 這可能導致循環導入。 Jest 可能是在處理模塊加載的通用 try<>catch 塊中捕獲此錯誤。
下面為我工作。 創建 babel.config.js 文件。
module.exports = {
presets: [
[ '@babel/preset-env', { targets: { esmodules: true } } ],
[ '@babel/preset-react', { runtime: 'automatic' } ],
],
};
對於任何在這個問題上苦苦掙扎的人,上述答案都不適合他/她。
經過大約很長時間的搜索,我找到了這個解決方案
編輯jest.config.js以添加transformIgnorePatterns
//jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
testMatch: ["**/__tests__/**/*.ts?(x)", "**/?(*.)+(test).ts?(x)"],
transform: {
"^.+\\.(js|ts)$": "ts-jest",
},
transformIgnorePatterns: [
"/node_modules/(?![@autofiy/autofiyable|@autofiy/property]).+\\.js$",
"/node_modules/(?![@autofiy/autofiyable|@autofiy/property]).+\\.ts$",
"/node_modules/(?![@autofiy/autofiyable|@autofiy/property]).+\\.tsx$",
],
}
將要忽略的包放在[]
,並用|
分隔它們
就我而言[@autofiy/autofiyable|@autofiy/property]
我將開玩笑的更新添加到我的
package.json<\/code>
"jest": {
"transformIgnorePatterns": [
"node_modules/(?!(<package-name>|<second-package-name>)/)"
]
},
下面對我有用
module.exports = {
presets: [
["@babel/preset-env", { targets: { node: "current" } }],
"@babel/preset-typescript", "@babel/react"
]
};
無法讓它與轉換一起工作,我最終得到了 mocking 依賴項:
創建文件:<path>/react-markdown.js
import React from 'react';
function ReactMarkdown({ children }){
return <>{children}</>;
}
export default ReactMarkdown;
在 jest.config.js 文件中添加:
module.exports = {
moduleNameMapper: {
'react-markdown': '<path>/mocks/react-markdown.js',
},
};
在 https 上歸功於 juanmartinez://github.com/remarkjs/react-markdown/issues/635
我更新了一些依賴項(react、jest 和其他),我也得到了錯誤:
Jest 遇到意外標記 - SyntaxError:無法在模塊外使用 import 語句
我有需要轉換的開發依賴項。
我首先做的是重新開始:
$ jest --init
現在生成了一個 jest.config.js(之前我的 package.json 中只有 Jest 配置)。
在詳細信息下的錯誤消息中,您可以看到報告模塊,對我來說它看起來像這樣:
詳細信息:/<project_root>/node_modules/axios/index.js:1
在 jest.config.js 中添加以下轉換忽略解決了我的問題:
transformIgnorePatterns: [
"node_modules/(?!(jest-)?react-native|axios(.*)|react-(native|universal|navigation)-(.*)|@react-native-community/(.*)|@react-navigation/(.*)|bs-platform|(@[a-zA-Z]+/)?(bs|reason|rescript)-(.*)+)"
],
axios 模塊現在被很好地編譯並且沒有再出現問題,希望這有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.