Если у кого-то есть опыт настройки Jest для тестирования приложения React, я буду вечно благодарен за помощь. Я пытаюсь настроить Jest для тестирования простого файла JSX, но получаю следующую ошибку. Это кажется простым делом, но я следовал каждому официальному руководству из документов Babel, Jest и babel-jest, а также всем сообщениям StackOverflow, которые я мог найти, и проблема все еще сохраняется.
- Мое приложение использует Babel и Webpack для переноса файлов JSX в JS.
- Jest отлично работает при обычном тестировании. js файлов.
- У меня есть и файл babel.config. js, и файл .babelr c (перечислены ниже), после попытки выполнить несколько потоков решений.
- Я использую Ubuntu на WSL2.
> jest --coverage
(node:4689) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
PASS database/index.test.js
FAIL client/index.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: /home/jsim0809/client/index.jsx: Unexpected token (5:16)
3 | import QA from './components/QA';
4 |
> 5 | ReactDOM.render(<QA />, document.getElementById('q-a'));
| ^
6 |
7 | export default ReactDOM.render;
8 |
Вот как выглядит мой репо:
// package.json
{
"name": "",
"version": "",
"description": "",
"author": "",
"license": "",
"engines": {
"node": ">=6.13.0"
},
"scripts": {
"start": "node server/index.js",
"start-dev": "nodemon server/index.js",
"build": "webpack",
"build-dev": "webpack --watch",
"seed": "node database/seedDB.js",
"test": "jest --coverage",
"jestinit": "jest --init",
"lint": "eslint ."
},
"dependencies": {
"@babel/plugin-proposal-class-properties": "^7.8.3",
"@babel/plugin-transform-runtime": "^7.8.3",
"babel-jest": "^25.1.0",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.2",
"express": "^4.17.1",
"faker": "^4.1.0",
"jest": "^25.1.0",
"jest-environment-enzyme": "^7.1.2",
"jest-enzyme": "^7.1.2",
"mongoose": "^5.9.4",
"nodemon": "^2.0.2",
"path": "^0.12.7",
"react": "^16.13.0",
"react-dom": "^16.13.0",
"webpack": "^4.42.0",
"webpack-cli": "^3.3.11"
},
"devDependencies": {
"@babel/core": "^7.8.7",
"@babel/preset-env": "^7.8.7",
"@babel/preset-react": "^7.8.3",
"babel-loader": "^8.0.6",
"eslint": "^6.8.0",
"eslint-config-airbnb": "^18.0.1",
"eslint-plugin-import": "^2.20.1",
"eslint-plugin-jsx-a11y": "^6.2.3",
"eslint-plugin-react": "^7.19.0",
"eslint-plugin-react-hooks": "^1.7.0"
},
"jest": {
"setupFilesAfterEnv": [
"<rootDir>testing/setupTests.js",
"jest-enzyme"
],
"testEnvironment": "enzyme"
}
}
// client/index.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import QA from './components/QA';
ReactDOM.render(<QA />, document.getElementById('q-a'));
export default ReactDOM.render;
// client/index.test.js
import React from 'react';
import { shallow, mount, render } from 'enzyme';
import ReactDOMRender from './index';
test('checks that the overall render method was called.', () => {
expect(ReactDOMRender).toHaveBeenCalled();
});
// public/index.html
<!DOCTYPE html>
<html>
<head>
<link href="./style.css" rel="stylesheet">
</head>
<body>
<div id="q-a">This will disappear when the React component loads.</div>
</body>
<script src="bundle.js"></script>
</html>
// babel.config.js
module.exports = {
presets: [
[
'@babel/preset-env',
{
targets: {
node: 'current',
},
},
],
'@babel/preset-react',
],
plugins: [
'@babel/plugin-proposal-class-properties',
'@babel/plugin-transform-runtime',
],
};
// .babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
// jest.config.js
module.exports = {
clearMocks: true,
coverageDirectory: "coverage",
testEnvironment: "node",
transform: {
'^.+\\.js$': 'babel-jest',
},
};
// webpack.config.js
const path = require('path');
module.exports = {
entry: path.join(__dirname, 'client', 'index.jsx'),
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js',
},
module: {
rules: [
{ test: /\.(js|jsx)$/, exclude: /node_modules/, loader: 'babel-loader' },
],
},
resolve: {
extensions: ['.js', '.jsx'],
},
devtool: 'inline-source-map',
mode: 'development',
};
Буду очень признателен за любые указатели. Спасибо.