gpt4 book ai didi

javascript - 错误没有 Jest : This usually means that you are trying to import a file which Jest cannot parse, 例如它不是普通的 JavaScript

转载 作者:行者123 更新时间:2023-12-01 17:19:17 27 4
gpt4 key购买 nike

我正在尝试使用 React 运行 Jest,我使用 --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;

这是我的文件 package.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"
]
}
}

这是我的 Babel.js:
{
"presets": ["@babel/preset-env"],
"plugins": [
"@babel/plugin-proposal-object-rest-spread",
"@babel/plugin-transform-async-to-generator"
]
}

按照 Github 上的项目链接:
User Registration Github

最佳答案

谢谢大家,除了必须安装 babel-jest ,之前还得做一些配置。

第一。我执行了命令

npm run eject



在项目中;

2 在“packge.json”文件中,我更改了“testMatch”以找到我在项目根目录中创建的测试文件夹;

第三,我创建了一个适配器文件以在测试前运行:
//<rootDir>/__tests__/setup.js
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

Enzyme.configure ({adapter: new Adapter ()});

4 添加库:

enzyme enzyme-adapter-react-16 react-test-render



`

然后它起作用了。

关于javascript - 错误没有 Jest : This usually means that you are trying to import a file which Jest cannot parse, 例如它不是普通的 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59414982/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com