作者:陈公子 | 来源:互联网 | 2023-09-15 08:19
我正在尝试使用 Jest 为我的reactjs
项目进行单元测试。
当我想测试组件的渲染时,出现以下错误:
SyntaxError: /Users/jk/EpitechProjects/T-WEB-700/CountOfMoney_18/front/src/tests/components/Navbar.test.js:
Support for the experimental syntax 'jsx' isn't currently enabled (9:29):
7 |
8 | test('Navbar : should render navbar', ()=>{
> 9 | const wrapper = shallow();
| ^
10 | expect(wrapper.find('nav').length).toBe(1);
Add @babel/preset-react (https://git.io/JfeDR) to the 'presets' section of
your Babel config to enable transformation. If you want to leave it as-is,
add @babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to
enable parsing.
但是,它似乎无法识别JSX
语法。
我已经尝试了两者@babel/preset-react
和@babel/plugin-syntax-jsx
建议,但仍然存在相同的错误。
这是我的一些配置文件:
jest.config.json
{
"setupFiles": [
"raf/polyfill",
"/src/setupTests.js"
],
"transform": {
"^.+.(js?)$": "babel-jest"
}
}
babel.config.js
module.exports = {
presets: [['@babel/preset-env', {targets: {node: 'current'}}]],
};
设置测试.js
//import '@testing-library/jest-dom';
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({
adapter: new Adapter()
});
包.json
{
"name": "front",
"version": "0.1.0",
"private": true,
"dependencies": {
...
"@testing-library/jest-dom": "^5.11.6",
"@testing-library/user-event": "^12.2.2",
...
"babel": "^6.23.0",
...
"react": "^17.0.1",
"react-dom": "^17.0.1",
...
"react-scripts": "4.0.0",
"react-test-renderer": "^17.0.1",
...
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"testJ": "jest --cOnfig=jest.config.json"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@babel/plugin-syntax-jsx": "^7.12.1",
"@babel/preset-react": "^7.12.10",
"@testing-library/react": "^11.2.2",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.5",
"jest": "^26.6.3"
回答
目前的罪魁祸首似乎是你的babel.config.js
,你需要让它与@babel/present-react
. 所以更新如下:
module.exports = {
presets: [
['@babel/preset-env', {targets: {node: 'current'}}],
['@babel/preset-react', {targets: {node: 'current'}}] // add this
]
};