[英]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.