我正在尝试运行Jest with React,我用--create-react-app启动了这个项目,然后添加了--babel,之后又添加了--jest,但是当我运行[yarn jest]时,屏幕上显示了这个错误,有人能帮我吗?
这是错误:
FAIL src/pages/users/__tests__/add.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: /usr/lib/myProjects/tryning/src/pages/users/add/index.js: Unexpected token (124:8)
122 |
123 | return (
> 124 | <>
| ^
125 | <Top />
126 | <Menu />
127 | <div className="user-add-form">
at Parser.raise (node_modules/@babel/parser/src/parser/location.js:41:63)
at Parser.unexpected (node_modules/@babel/parser/src/parser/util.js:160:16)
at Parser.parseExprAtom (node_modules/@babel/parser/src/parser/expression.js:1143:20)
at Parser.parseExprSubscripts (node_modules/@babel/parser/src/parser/expression.js:553:23)
at Parser.parseMaybeUnary (node_modules/@babel/parser/src/parser/expression.js:533:21)
at Parser.parseExprOps (node_modules/@babel/parser/src/parser/expression.js:301:23)
at Parser.parseMaybeConditional (node_modules/@babel/parser/src/parser/expression.js:256:23)
at Parser.parseMaybeAssign (node_modules/@babel/parser/src/parser/expression.js:186:21)
at Parser.parseParenAndDistinguishExpression (node_modules/@babel/parser/src/parser/expression.js:1312:16)
at Parser.parseExprAtom (node_modules/@babel/parser/src/parser/expression.js:1050:21)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 4.267s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
这是文件测试:
import React from 'react';
import Enzyme, { mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });
const addUser = require('../add/index');
describe('MyComponent', () => {
it('works', () => {
expect(addUser.fieldCheck('Nelson')).to(true);
});
});
这是我正在尝试测试的文件:
import React, { useState } from 'react';
import './style.css';
import Menu from '../../../components/menu';
import Top from '../../../components/top';
import { Link } from 'react-router-dom';
const AddUser = () => {
const [nameInput, setName] = useState('');
const [cpfInput, setCpf] = useState('');
const [userInput, setUser] = useState('');
const [passInput, setPass] = useState('');
let accounts = [];
var accountsJson = JSON.parse(localStorage.getItem('tableUser'));
const fieldCheck = field => {
if (field.value === null || field.value.trim() === ""){
field.style = "border: 1px solid #ff0000";
return false;
}
else{
field.style = "border: 1px solid #339680";
return true;
}
}
const account = {
name: '',
cpf: '',
user: '',
pass: '',
};
const finalWarning = (operation, error) => {
switch (operation) {
case 'save':
return 'Save with sucess!';
case 'error':
return 'An error has occurred: '
.concat(error)
.concat("!");
case 'cancel':
return 'The action has been undone!';
case 'empty':
return 'Fields on red not can are empty!'
default:
return 'Do not possible return in [finalWarning] >52';
}
}
const confirmSave = () => {
var op = window.confirm("Are you sure you want to save?");
return op;
}
const cleanFields = () => {
setName('');
setCpf('');
setUser('');
setPass('');
}
const emptyFields = inputsElements => {
var haveEmpty = false;
inputsElements.map(input => {
if (document.getElementsByName(input)[0].value === "") {
document.getElementsByName(input)[0].style = "border: 1px solid #ff0000";
haveEmpty = true;
}
else {
haveEmpty = false;
}
});
if (haveEmpty) {
alert(finalWarning('empty'));
return true;
}
else {
return false;
}
}
const addAccount = account => {
accounts.push(account);
localStorage.setItem('tableUser', JSON.stringify(accounts));
}
const handleFormSubmit = event => {
event.preventDefault();
account.name = nameInput;
account.cpf = cpfInput;
account.user = userInput;
account.pass = passInput;
if (!emptyFields(['nameInput', 'cpfInput', 'userInput', 'passInput'])) {
if (confirmSave())
try {
accounts = [];
for (var i in accountsJson)
accounts.push(accountsJson[i]);
addAccount(account);
cleanFields();
alert(finalWarning('save'));
window.location.href = "/users";
}
catch (e) {
alert(finalWarning('error', e));
alert(e);
window.location.href = "/users";
}
else
alert(finalWarning('cancel'));
}
}
return (
<>
<Top />
<Menu />
<div className="user-add-form">
<div className="line-top"></div>
<form method="post" id="user-add-form" onSubmit={handleFormSubmit}>
<div className="user-add-fields">
Name
<input
onChange={e => setName(e.target.value)}
name="nameInput"
value={nameInput}
type="text"
placeholder="Insert name."
onBlur={e => fieldCheck(e.target)}
/>
CPF
<input
onChange={e => setCpf(e.target.value)}
name="cpfInput"
value={cpfInput}
type="text"
placeholder="Insert cpf."
onBlur={e => fieldCheck(e.target)}
/>
User
<input
onChange={e => setUser(e.target.value)}
name="userInput"
value={userInput}
type="text"
placeholder="Insert user."
onBlur={e => fieldCheck(e.target)}
/>
Password
<input
onChange={e => setPass(e.target.value)}
name="passInput"
value={passInput}
type="password"
placeholder="Insert password."
onBlur={e => fieldCheck(e.target)}
/>
</div>
<button
type="submit"
className=" button user-add-save-button"
>
Save
</button>
</form>
<Link to="/Users" className="button user-add-cancel-button" >
Cancel
</Link>
</div >
</>
);
}
export default AddUser;
这是我的文件包. json:
{
"name": "trying",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/react": "^9.3.3",
"babel": "^6.23.0",
"enzyme": "^3.10.0",
"enzyme-adapter-react-16": "^1.15.1",
"jest": "^24.9.0",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-router-dom": "^5.1.2",
"react-scripts": "3.2.0",
"tab": "^1.0.0",
"tabs": "^0.2.0",
"webfontloader": "^1.6.28"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "jest",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
这是我的巴别塔。
{
"presets": ["@babel/preset-env"],
"plugins": [
"@babel/plugin-proposal-object-rest-spread",
"@babel/plugin-transform-async-to-generator"
]
}
点击Github上的项目链接:User Registration Github
1条答案
按热度按时间qzwqbdag1#
谢谢大家,除了必须安装babel-jest,我还必须做一些配置之前。
1.我执行了命令
npm运行弹出
在项目中;
2nd在"packge.json"文件中,我更改了"testMatch"以查找test文件夹,该文件夹是我在项目根目录中创建的;
3.我创建了一个适配器文件,以便在测试之前运行:
4.添加库:
酶酶-衔接子-React-16React-测试-呈现
'
然后就成功了。