爱杰斯? 请考虑支持我们的集体:👉 https://opencollective.com/jest/donate
在 React 应用程序中尝试使用 Jest 运行测试时,出现Jest encountered an unexpected token
错误。 我复制了Link
组件并直接从这里测试。 这是错误:
FAIL src/components/Link.test.js
● 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:
SyntaxError: C:\workspace\react\testapp\src\components\Link.test.js: Unexpected token (8:4)
6 | test('Link changes the class when hovered', () => {
7 | const component = renderer.create(
> 8 | <Link page="http://www.facebook.com">Facebook</Link>,
| ^
9 | );
10 | let tree = component.toJSON();
11 | expect(tree).toMatchSnapshot();
at Parser.raise (node_modules/@babel/parser/lib/index.js:3938:15)
at Parser.unexpected (node_modules/@babel/parser/lib/index.js:5247:16)
at Parser.parseExprAtom (node_modules/@babel/parser/lib/index.js:6327:20)
at Parser.parseExprSubscripts (node_modules/@babel/parser/lib/index.js:5923:21)
at Parser.parseMaybeUnary (node_modules/@babel/parser/lib/index.js:5902:21)
at Parser.parseExprOps (node_modules/@babel/parser/lib/index.js:5811:21)
at Parser.parseMaybeConditional (node_modules/@babel/parser/lib/index.js:5783:21)
at Parser.parseMaybeAssign (node_modules/@babel/parser/lib/index.js:5730:21)
at Parser.parseExprListItem (node_modules/@babel/parser/lib/index.js:6994:18)
at Parser.parseCallExpressionArguments (node_modules/@babel/parser/lib/index.js:6123:22)
这是我的package.json
{
"name": "testapp",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "webpack-dev-server --config ./config/webpack.config.development.js",
"build": "webpack -p --config ./config/webpack.config.production.js",
"test": "jest"
},
"dependencies": {
"axios": "^0.18.0",
"moment": "^2.22.2",
"polished": "^2.0.3",
"prop-types": "^15.6.2",
"react": "^16.4.2",
"react-delay-render": "^0.1.2",
"react-dom": "^16.4.2",
"react-imported-component": "^4.6.2",
"react-router-dom": "^4.3.1",
"simple-grid": "^1.0.1",
"styled-components": "^3.4.5",
"uuid": "^3.3.2",
"validator": "^10.7.0"
},
"devDependencies": {
"@babel/core": "^7.0.0",
"@babel/plugin-proposal-class-properties": "^7.0.0",
"@babel/plugin-syntax-dynamic-import": "^7.0.0",
"@babel/preset-env": "^7.0.0",
"@babel/preset-react": "^7.0.0",
"babel-core": "7.0.0-bridge.0",
"babel-jest": "^23.4.2",
"babel-loader": "^8.0.0",
"babel-plugin-styled-components": "^1.6.0",
"css-loader": "^1.0.0",
"html-webpack-plugin": "^3.2.0",
"jest": "^23.5.0",
"mini-css-extract-plugin": "^0.4.2",
"react-test-renderer": "^16.4.2",
"regenerator-runtime": "^0.12.1",
"style-loader": "^0.23.0",
"webpack": "^4.17.1",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.7"
}
}
这是我的.babelrc
文件(位于根目录中):
{
"plugins": [
"@babel/plugin-proposal-class-properties",
"babel-plugin-styled-components",
"@babel/plugin-syntax-dynamic-import"
],
"presets": ["@babel/preset-env", "@babel/preset-react"],
"env": {
"development": {
"plugins": [
"@babel/plugin-proposal-class-properties",
["babel-plugin-styled-components", { "displayName": true }],
"@babel/plugin-syntax-dynamic-import"
],
"presets": ["@babel/preset-env", "@babel/preset-react"]
},
"test": {
"plugins": [
"@babel/plugin-proposal-class-properties",
["babel-plugin-styled-components", { "displayName": true }],
"@babel/plugin-syntax-dynamic-import"
],
"presets": ["@babel/preset-env", "@babel/preset-react"]
},
"production": {
"plugins": [
"@babel/plugin-proposal-class-properties",
"babel-plugin-styled-components",
"@babel/plugin-syntax-dynamic-import"
],
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
}
}
重现行为的步骤:
yarn add --dev babel-jest babel-core@^7.0.0-0 @babel/core
安装 Jestyarn test
npx envinfo --preset jest
将结果粘贴到此处:
OS: Windows 10
CPU: x64 Intel(R) Xeon(R) CPU E3-1505M v6 @ 3.00GHz
Binaries:
Yarn: 1.5.1 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
npm: 5.6.0 - C:\Program Files\nodejs\npm.CMD
我也有同样的问题。
同样的问题在这里。
同样的问题在这里..稍微复杂一点,因为我正在使用 monorepo。
@fabioSalimbeni @hoaiduyit @mikedloss我已经使用 Babel 7 在 Lerna monorepo 中通过了我的 React 和 React Native 测试( Jest
和enzyme
)。
如果您正在使用 monorepo,则需要使用带有babel.config.js
的新 Babel 配置: https ://babeljs.io/docs/en/v7-migration
这是monorepo 根的babel.config.js
:
module.exports = {
overrides: [
{
test: 'platforms/webApp1',
extends: 'platforms/webApp1/babel.config.js'
},
{
test: 'platforms/webApp2',
extends: 'platforms/webApp2/babel.config.js'
}
]
};
这就是我的babel.config.js
对于webApp1
一个 monorepo 应用程序的样子:
module.exports = {
env: {
test: {
presets: [
[
'@babel/preset-env',
{
modules: 'commonjs',
debug: false
}
],
'@babel/preset-flow',
'@babel/preset-react'
],
plugins: [
'@babel/plugin-syntax-dynamic-import',
'@babel/plugin-proposal-class-properties'
]
},
production: {
presets: [
['@babel/preset-env', { modules: false }],
'@babel/preset-flow',
'@babel/preset-react'
],
plugins: [
'@babel/plugin-syntax-dynamic-import',
'@babel/plugin-proposal-class-properties'
]
},
development: {
presets: [
['@babel/preset-env', { modules: false }],
'@babel/preset-flow',
'@babel/preset-react'
],
plugins: [
'@babel/plugin-syntax-dynamic-import',
'@babel/plugin-proposal-class-properties'
]
}
}
};
这是 Jest 配置:
"jest": {
"verbose": true,
"clearMocks": true,
"collectCoverage": true,
"setupTestFrameworkScriptFile": "<rootDir>/config/setupTest.js",
"transform": {
"^.+\\.js$": "babel-jest"
},
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|scss)$": "<rootDir>/__mocks__/styleMock.js"
}
}
setupTest.js
看起来像:
const Enzyme = require('enzyme');
const Adapter = require('enzyme-adapter-react-16');
Enzyme.configure({ adapter: new Adapter() });
fileMocks.js
看起来像:
module.exports = 'i-am-a-stubbed-file';
styleMocks.js
看起来像:
module.exports = {};
您还需要在每个应用程序的package.json
中添加一些 Babel 插件和babel-core
版本作为devDependencies
:
...
"@babel/cli": "^7.0.0",
"@babel/core": "^7.0.0",
"@babel/plugin-proposal-class-properties": "^7.0.0",
"@babel/plugin-syntax-dynamic-import": "^7.0.0",
"@babel/preset-env": "^7.0.0",
"@babel/preset-flow": "^7.0.0",
"@babel/preset-react": "^7.0.0",
"babel-core": "7.0.0-bridge.0",
"babel-eslint": "^9.0.0",
"babel-jest": "^23.4.2",
"babel-loader": "^8.0.2",
...
"jest": "^23.5.0",
"jest-cli": "^23.5.0",
...
3天后,我才找到了这个问题的解决方案。
有两种解决方案:
您可以将文件名从.babelrc
更改babel.config.js
,这将起作用。
##解决方案2:
我正在使用这种方式。
创建一个这样的转换文件(我的是jest-transforme.js
):
const config = {
babelrc: false,
presets: [
[
"@babel/env",
{
modules: false
}
],
"@babel/react"
],
plugins: [
["@babel/plugin-proposal-decorators", { legacy: true }],
["@babel/plugin-proposal-class-properties", { loose: true }],
"transform-es2015-modules-commonjs"
]
};
module.exports = require("babel-jest").createTransformer(config);
这是我的jest.config.js
:
module.exports = {
collectCoverageFrom: ["src/**/*.{js,jsx,mjs}"],
testMatch: ["<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}", "<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"],
transform: {
"^.+\\.(js|jsx|mjs)$": "<rootDir>/config/jest/jest-transformer.js"
},
transformIgnorePatterns: ["[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"]
};
我还有我的.babelrc
``
const 环境 = require("./env-config.js");
模块.出口 = {
预设:[
[
"下一个/巴别塔",
{
“预设环境”:{
使用BuiltIns:“条目”
}
}
]
],
插件: [
["styled-components", { ssr: true, displayName: true, preprocess: false }],
[
“模块解析器”,
{
根: [”。/”]
}
]
],
环境:{
开发:{
插件: [
[“转换定义”,环境],
[“模块解析器”,{根:[“./”]}],
“变换-装饰器-遗产”,
“转换类属性”
]
},
建造: {
插件: [
[“转换定义”,环境],
[“模块解析器”,{根:[“./”]}],
“变换-装饰器-遗产”,
“转换类属性”
]
},
生产: {
预设:[
[
"minify", // 为什么在这里添加 minify,我们在整个代码包上运行 uglify
{
mangle:假的,
评价:假
}
]
],
插件: [
[“转换定义”,环境],
["@babel/plugin-proposal-decorators", { legacy: true }],
[“@babel/plugin-proposal-class-properties”,{松散:真实}],
[“模块解析器”,{根:[“./”]}]
],
评论:假的,
紧凑:真实,
缩小:真实
}
}
};
````
希望这可以让你们通过这个问题。 欢呼。
@GeorgianSorinMaxim问题是我的玩笑应用程序忽略.babelrc
文件,更改为babel.config.js
将解决问题,但我还是解决了它,我的答案高于此评论。
感谢@GeorgianSorinMaxim @hoaiduyit最后我只是通过为 babel-jest 创建自定义转换器来解决它。 无需其他更改。
Babel 7 似乎需要babel.config.js
才能正常工作,使用它而不是 babelrc
babel-jest
仍然依赖于 Babel 6 中的babel-core
,如果你想使用Babel 7你可以使用
这个变压器babel7-jest
babel-jest
在 babel 7 上工作得很好,不需要自定义转换器
@SimenB我将我的.babelrc
重命名为babel.config.js
但它仍然显示出带有意外令牌的错误。 不过它适用于 babel7-pre.42。 还有其他常见的遗漏吗? :) 谢谢。
@alexindigo看看这个如何写babel.config.js
是的,运行yarn upgrade --latest
解决了这个问题:)
@alexindigo @hoaiduyit你们到底是怎么知道babel.config.js
? 解决同样的问题并找到您的解决方案,我在想自己......_“嗯,这不可能奏效,但无论如何我都会尝试。”_但果然它做到了 lulz。 谢谢
Jest & 酶配置:在 package.json 中添加以下代码
"jest": {
"testEnvironment": "jsdom",
"moduleDirectories": [
"src",
"node_modules"
],
"moduleNameMapper": {
"\\.(css|scss)$": "<rootDir>/__mocks__/styleMock.js",
"\\.(jpg|gif|ttf|eot|svg)$": "<rootDir>/__mocks__/fileMock.js"
},
"transform": {
"^.+\\.(js|jsx)$": "babel-jest",
".+\\.(css|styl|less|sass|scss)$": "<rootDir>/node_modules/jest-css-modules-transform"
},
"setupTestFrameworkScriptFile": "<rootDir>/setupTests.js",
"setupFiles": [
"<rootDir>setup.js"
],
"moduleFileExtensions": [
"css",
"scss",
"js",
"json",
"jsx"
],
"testRegex": "\/test\/spec\/.*\\.js$",
"transformIgnorePatterns": [
"/node_modules/(?!test-component).+\\.js$"
]
}
用于设置酶 => setup.js
import { configure } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
configure({ adapter: new Adapter() })
对于 setupTestFrameworkScriptFile : setupTests.js global.fetch = require('jest-fetch-mock')
const { JSDOM } = require('jsdom')
const jsdom = new JSDOM('<!doctype html><html><body></body></html>')
const { window } = jsdom
const exposedProperties = ['window', 'navigator', 'document']
const { document } = new JSDOM('').window
global.document = document
global.window = document.defaultView
global.HTMLElement = window.HTMLElement
global.HTMLAnchorElement = window.HTMLAnchorElement
Object.keys(document.defaultView).forEach(property => {
if (typeof global[property] === 'undefined') {
exposedProperties.push(property)
global[property] = document.defaultView[property]
}
})
global.navigator = {
userAgent: 'node.js',
}
只是 .tsx 文件面临同样的问题?
只是传播新闻,Jest v24 已更新为在内部使用 Babel 7,不再需要使用babel bridge
或babel7-jest
https://twitter.com/i/web/status/1088904207653105664
我将.babelrc
重命名babel.config.js
并升级到 Babel7,但仍然出现与以前相同的错误。 我的babel.config.js
文件:
module.exports = function (api) {
api.cache(true);
const presets = ["@babel/preset-env"];
return {
presets
};
}
我安装了@babel/preset-react
并将其添加到我的babel.config.js
文件中。 修复了错误。
我的babel.config.js
文件没有被babel-jest
检测到,因为我把它放在__test__
目录中。 我将它移动到package.json
所在的顶级目录,一切正常。
我通过执行以下操作解决了类似的问题:
1-添加酶设置文件并写入以下内容:
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });
2- 将 jest 配置添加到您的 package.json 中,如下所示:
"jest": {
"setupFilesAfterEnv": [
"./path to your setup file/setupEnzyme.js"
]
}
3- 将 .babelrc 文件添加到您的根路径并在其中写入以下内容:
{
"env": {
"test": {
"presets": [
"@babel/preset-env",
"@babel/preset-react"
]
}
}
}
4-如果您在测试中的“expect”关键字出现错误,只需运行npm install -D chai
并在您的测试代码中像import { expect } from 'chai';
一样导入 expect 函数
如果仍然出现错误,请尝试安装像npm install -D @babel/core @babel/preset-env @babel/preset-react
这样的 babel 依赖项
希望这可以帮助。
3天后,我才找到了这个问题的解决方案。
有两种解决方案:解决方案1:
您可以将文件名从
.babelrc
更改babel.config.js
,这将起作用。
我没有 .babelrc 文件,所以我认为反向操作也应该起作用,并使用来自 babel.config.js 的预设信息创建了一个 .babelrc 文件。 (我创建了一个额外的文件,我没有重命名原始文件)
再次运行测试后,我收到一个新错误: Requires Babel "^7.0.0-0", but was loaded with "6.26.3"
。
我用谷歌搜索了那个错误,它把我带到了这里。 我按照说明( npm install [email protected]
)进行了测试,现在正在运行并通过。
只是传播新闻,Jest v24 已更新为在内部使用 Babel 7,不再需要使用
babel bridge
或babel7-jest
https://twitter.com/i/web/status/1088904207653105664
升级到 Jest v24 为我解决了这个问题:)
得到unexpected token
错误
> 10 | const browser;
(末尾的分号)
我的 package.json
"dependencies": {
"@babel/cli": "^7.2.3",
"@babel/core": "^7.3.4",
"@babel/register": "^7.0.0",
"assert": "^1.4.1",
"chai": "^4.2.0",
"jest-puppeteer": "^4.0.0",
"screen-info": "^1.0.1",
"screenres": "^2.0.1"
},
"devDependencies": {
"@babel/plugin-transform-modules-commonjs": "^7.2.0",
"@babel/preset-env": "^7.3.4",
"babel-jest": "^24.5.0",
"babel-preset-env": "^1.7.0",
"babel-preset-jest": "^24.3.0",
"jest": "^24.5.0",
"jest-cli": "^24.5.0",
"puppeteer": "^1.13.0"
},
"jest": {
"transformIgnorePatterns": [
"/node_modules/(?!@babel).+\\.js$"
],
"transform": {
"^.+\\.js?$": "babel-jest"
}
},
babel.config.js
module.exports = {
presets: [
[
'@babel/preset-env',
{
targets: {
node: 'current'
},
},
'jest'
]
],
env: {
test: {
plugins: ['@babel/plugin-transform-modules-commonjs']
}
}
}
经过测试的 hoaiduyit 解决方案。 这行得通。 我只需要添加 babel.config.js,在 jest.config.js 中安装babel-jest
transform/transpile jest
3天后,我才找到了这个问题的解决方案。
有两种解决方案:解决方案1:
您可以将文件名从
.babelrc
更改babel.config.js
,这将起作用。解决方案2:
我正在使用这种方式。
创建一个这样的转换文件(我的是jest-transforme.js
):const config = { babelrc: false, presets: [ [ "@babel/env", { modules: false } ], "@babel/react" ], plugins: [ ["@babel/plugin-proposal-decorators", { legacy: true }], ["@babel/plugin-proposal-class-properties", { loose: true }], "transform-es2015-modules-commonjs" ] }; module.exports = require("babel-jest").createTransformer(config);
这是我的
jest.config.js
:module.exports = { collectCoverageFrom: ["src/**/*.{js,jsx,mjs}"], testMatch: ["<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}", "<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"], transform: { "^.+\\.(js|jsx|mjs)$": "<rootDir>/config/jest/jest-transformer.js" }, transformIgnorePatterns: ["[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"] };
我还有我的
.babelrc
const enviroments = require("./env-config.js"); module.exports = { presets: [ [ "next/babel", { "preset-env": { useBuiltIns: "entry" } } ] ], plugins: [ ["styled-components", { ssr: true, displayName: true, preprocess: false }], [ "module-resolver", { root: ["./"] } ] ], env: { dev: { plugins: [ ["transform-define", enviroments], ["module-resolver", { root: ["./"] }], "transform-decorators-legacy", "transform-class-properties" ] }, build: { plugins: [ ["transform-define", enviroments], ["module-resolver", { root: ["./"] }], "transform-decorators-legacy", "transform-class-properties" ] }, production: { presets: [ [ "minify", // why add minify here, we run uglify over the whole code bundles { mangle: false, evaluate: false } ] ], plugins: [ ["transform-define", enviroments], ["@babel/plugin-proposal-decorators", { legacy: true }], ["@babel/plugin-proposal-class-properties", { loose: true }], ["module-resolver", { root: ["./"] }] ], comments: false, compact: true, minified: true } } };
希望这可以让你们通过这个问题。 欢呼。
tks你的方法~这个方法可以正确解决我的问题!
嗨 - 我在这个线程中尝试了几件事,但似乎没有任何效果。 主要错误很奇怪 b/c 它似乎指向没有意义的行号,几乎就像源代码和试图运行的实际代码不对齐一样..
这个错误,Jest 遇到了一个意外的令牌,仍然存在。 我在 Jest > 24 上,没有打字稿,它最近(6 个月前~)弹出了一个 react-create-app。 清除缓存和删除 node_modules 没有帮助。 也许有人可以准确解释 jest 需要什么配置才能正确转换和运行,以及我的确切错误给出了什么提示......
FAIL __e2e__/chat/sms.spec.js
● 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:
/Users/ben/dev/app/webui/node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:17
export default function _asyncToGenerator(fn) {
^^^^^^
SyntaxError: Unexpected token export
5 | afterEach(async () => {
6 | await logout();
> 7 |
| ^
8 | await page.evaluate(() => {
9 | localStorage.clear();
10 | });
at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:471:17)
at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:513:25)
at Object.<anonymous> (__e2e__/chat/sms.spec.js:7:49)
谢谢你们,
Jenkins 因这个问题而失败,是否有一些可行的解决方案?
对于使用 Create-React-App 的任何人,将transformignorepatterns
到您的 package.json 不会解决问题,因为在使用 CRA 时,只能在 package.json 中更改某些笑话配置。
我在 Jest 选择内部库时遇到了问题,无论我从这个库中导入什么,Jest 都会显示“意外令牌”错误。
要解决此问题,您可以将测试脚本更改为以下内容:
"test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!(<your-package-goes-here>)/)'",
大家好,我正在努力用我的小项目 JetSet 进行单元测试,这个项目是用 React Native 编写的。 我搜索了 2 天来解决这个问题,我试图编辑像 babel.config.js 这样的东西,删除那个文件,然后创建 .babel 文件(并添加一些东西)。
_错误报告:_
D:\jetset\JetSetApp>jest SaveData.test.js
失败 __test__/SaveData.test.js
● 测试套件运行失败
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:
D:\jetset\JetSetApp\node_modules\expo-file-system\build\index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import * as FileSystem from './FileSystem';
^
SyntaxError: Unexpected token *
1 | import React, { Component } from 'react'
2 | import { View, Text, TouchableOpacity, TextInput, StyleSheet } from 'react-native'
> 3 | import { documentDirectory, getInfoAsync, readDirectoryAsync, readAsStringAsync, writeAsStringAsync, deleteAsync } from 'expo-file-system';
| ^
4 |
5 | /**
6 | * This class primarily serves to handle files within the phone system so that results can be stored
at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)
at Object.<anonymous> (app/resources/SaveData/SaveData.js:3:1)
测试套件:1 个失败,总共 1 个
测试:0 总
快照:共 0 个
时间:3.509s
运行所有匹配 /SaveData.test.js/i 的测试套件。
_ babel.config.js _
module.exports = 函数(api){
api.cache(true);
返回 {
预设:['babel-preset-expo'],
};
};
_ package.json _
{
"main": "node_modules/expo/AppEntry.js",
“脚本”:{
"start": "展会开始",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "博览会开始 --web",
"eject": "博览会弹出",
“测试”:“开玩笑”
},
“开玩笑”:{
“预设”:“反应原生”
},
“依赖关系”:{
"博览会": "^34.0.1",
"expo-file-system": "^6.0.2",
"expo-mail-composer": "^6.0.0",
"时刻": "^2.24.0",
“反应”:“16.8.3”,
"react-dom": "^16.8.6",
"react-native": " https://github.com/expo/react-native/archive/sdk-34.0.0.tar.gz ",
"react-native-gesture-handler": "^1.3.0",
"react-native-selection-group": "^1.1.2",
"react-native-web": "^0.11.4"
},
“开发依赖”:{
"@babel/core": "^7.6.2",
"@babel/preset-env": "^7.6.2",
"babel-jest": "^24.9.0",
"babel-preset-expo": "^6.0.0",
"jest": "^24.9.0",
"道具类型": "^15.7.2",
"react-native-dismiss-keyboard": "^1.0.0",
"react-native-modal-datetime-picker": "^7.5.0",
“反应导航”:“^3.12.1”
},
“私人”:真的
}
仅供参考,我认为我们最终找到了一个非常愚蠢的解决方案,就像如果没有设置 NODE_ENV="test" ,整个构建系统就会表现不佳。
在较新版本的 React Jest 中内置因此在 package.json 中的测试脚本应该是"test": "react-scripts test"
代替"test": "jest"
在较新版本的 React Jest 中内置因此在 package.json 中的测试脚本应该是
"test": "react-scripts test"
代替"test": "jest"
非常感谢,为我解决了这个问题!
在尝试了很多之后,我的问题是:
.babelrc 文件中缺少"transform-es2015-modules-commonjs",
{
"presets": ["next/babel"],
"plugins": [
["styled-components", { "ssr": true, "displayName": true, "preprocess": false } ],
"transform-flow-strip-types",
"jsx-control-statements",
"import-glob",
"transform-es2015-modules-commonjs",
[
"import",
{
"libraryName": "antd",
"style": "css"
}
]
]
}
"jest": "^24.9.0",
"babel-jest": "23.6.0",
尝试更新你的 jest 和 babel-jest
我将
.babelrc
重命名babel.config.js
并升级到 Babel7,但仍然出现与以前相同的错误。 我的babel.config.js
文件:module.exports = function (api) { api.cache(true); const presets = ["@babel/preset-env"]; return { presets }; }
我安装了
@babel/preset-react
并将其添加到我的babel.config.js
文件中。 修复了错误。
这解决了我的问题,我安装了 @babel/preset-env 并添加到 babel.config.js 并修复了
谢谢@jmayergit
我已将 babel.rc 文件更改为 babel.config.js 文件,但它对我不起作用。 然后我看到了这个答案: https :
如果有导入插件,请将测试、开发和生产环境的插件分开。
我的 babel.config.js 文件现在看起来是这样的:
module.exports = {
presets: [
[
'next/babel',
],
],
env: {
test: {
},
dev: {
plugins: [
['import', { libraryName: 'antd', style: 'css' }],
],
},
production: {
plugins: [
['import', { libraryName: 'antd', style: 'css' }],
],
},
},
};
从 5 天起,我也在为这个错误而苦苦挣扎
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:
SyntaxError: C:\Users\SK-PC\Desktop\React-Course\expansify\src\test\components\MyNavbar.test.js: Unexpected token (5:28)
3 | import { MyNavbar } from '../../components/MyNavbar'
4 | test("Should return MyNavbar component", () => {
> 5 | const wrapper = shallow(<MyNavbar />)
| ^
6 | expect(wrapper.find('.navbar-brand').find('kbd').text()).toBe("Expensify")
7 | // const renderer = new ReactShallowRenderer()
8 | // renderer.render(<MyNavbar />)
at Parser._raise (node_modules/@babel/parser/src/parser/location.js:241:45)
at Parser.raiseWithData (node_modules/@babel/parser/src/parser/location.js:236:17)
at Parser.raise (node_modules/@babel/parser/src/parser/location.js:220:17)
at Parser.unexpected (node_modules/@babel/parser/src/parser/util.js:149:16)
at Parser.parseExprAtom (node_modules/@babel/parser/src/parser/expression.js:1144:20)
at Parser.parseExprSubscripts (node_modules/@babel/parser/src/parser/expression.js:539:23)
at Parser.parseMaybeUnary (node_modules/@babel/parser/src/parser/expression.js:519:21)
at Parser.parseExprOps (node_modules/@babel/parser/src/parser/expression.js:311:23)
at Parser.parseMaybeConditional (node_modules/@babel/parser/src/parser/expression.js:263:23)
at Parser.parseMaybeAssign (node_modules/@babel/parser/src/parser/expression.js:211:21)
PASS src/test/reducers/filters.test.js
Test Suites: 1 failed, 5 passed, 6 total
Tests: 29 passed, 29 total
Snapshots: 0 total
Time: 12.144s
Ran all test suites.
@fullstacksk
在较新版本的 React Jest 中内置因此在 package.json 中的测试脚本应该是
"test": "react-scripts test"
代替"test": "jest"
您可以在以下位置阅读文档:
https://jestjs.io/docs/en/tutorial-react
https://create-react-app.dev/docs/running-tests/#docsNav
@猫人1
我还没有安装像 create-react-app 或 react-scripts 这样的依赖项。
它会起作用吗?
"test": "react-scripts test"
代替"test": "jest"
现在它可以工作了,当我使用 babel-preset-jest 来测试带有 env 和 react 的选项时。 我已经删除了 babel-jeast。
为我工作:在babel.config.js
处包含“@babel/preset-react”
https://medium.com/@audreyhal/how -to-solve-jest-error-with-create-react-app-part-1-80f33aa1661a
在犯了一个愚蠢的错误并使用.ts
而不是.tsx
扩展名编写我的第一个测试文件后,我看到了这个错误。 与最初的问题相去甚远,但我认为它可能对某人有帮助 😄
最有用的评论
3天后,我才找到了这个问题的解决方案。
有两种解决方案:
解决方案1:
您可以将文件名从
.babelrc
更改babel.config.js
,这将起作用。##解决方案2:
我正在使用这种方式。
创建一个这样的转换文件(我的是
jest-transforme.js
):这是我的
jest.config.js
:我还有我的
.babelrc
``
const 环境 = require("./env-config.js");
模块.出口 = {
预设:[
[
"下一个/巴别塔",
{
“预设环境”:{
使用BuiltIns:“条目”
}
}
]
],
插件: [
["styled-components", { ssr: true, displayName: true, preprocess: false }],
[
“模块解析器”,
{
根: [”。/”]
}
]
],
环境:{
开发:{
插件: [
[“转换定义”,环境],
[“模块解析器”,{根:[“./”]}],
“变换-装饰器-遗产”,
“转换类属性”
]
},
建造: {
插件: [
[“转换定义”,环境],
[“模块解析器”,{根:[“./”]}],
“变换-装饰器-遗产”,
“转换类属性”
]
},
生产: {
预设:[
[
"minify", // 为什么在这里添加 minify,我们在整个代码包上运行 uglify
{
mangle:假的,
评价:假
}
]
],
插件: [
[“转换定义”,环境],
["@babel/plugin-proposal-decorators", { legacy: true }],
[“@babel/plugin-proposal-class-properties”,{松散:真实}],
[“模块解析器”,{根:[“./”]}]
],
评论:假的,
紧凑:真实,
缩小:真实
}
}
};
````
希望这可以让你们通过这个问题。 欢呼。