Test with enzyme: Unexpected token in mount() - reactjs

I'm trying to make enzyme tests in react.
I make this simple test that mount a import component and check the states:
import React from 'react';
import { expect } from 'chai';
import { mount } from 'enzyme';
import WorkOutForm from './workOutForm';
describe('<WorkOutForm>', () => {
describe('workoutForm component', () => {
it('should start a new workoutForm with empty state', () => {
const component = mount(<WorkOutForm />);
expect(component).toEqual({})
expect(component.state().tempoGasto).toEqual(null)
expect(component.state().tipoAtividade).toEqual(null)
expect(component.state().data).toEqual(null)
component.unmount()
})
})
})
But when i run npm run test i get:
Jest encountered an unexpected token const component =
mount()
I try to make like the doc but i can't see my error.
Obs: i follow the jest getting started and i run:
npm i --save babel-jest #babel/core #babel/preset-env --dev
i added a babel.config.js file in the root with this content:
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
};
and this is my webpack:
module: {
loaders: [{
test: /.js[x]?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react', '#babel/preset-env'],
plugins: ['transform-object-rest-spread']
}
}, {
test: /\.css$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader')
}, {
test: /\.woff|.woff2|.ttf|.eot|.svg*.*$/,
loader: 'file'
},
]
}

Please try adding the following in your package.json jest config:
"transform": {
"\\.js$": "<rootDir>/node_modules/babel-jest"
},
Make sure you install the babel-jest package first

Related

Module parse failed: Unexpected character '#' (1:0) with Storybook 6.1.11, Webpack 5.11.0, React 17.0.1

Trying to setup a react-app with all latest versions.
Github Repo Link
Trying to run storybook with sass file imported will result in below error. Trying to run without importing the styles, storybook works.
The same code works correctly when its run as npm start run with no warnings and errors.
I have configured css modules using #dr.pogodin/babel-plugin-react-css-modules with sass, webpack 5, react 17 and with latest packages.
ERROR in ./src/assets/stylesheets/app.scss 1:0
Module parse failed: Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> #import "./base.scss";
| #import "./generics/font.scss";
| #import "./generics/spacing.scss";
# ./stories/index.js 5:0-44 8:2-10:4 8:58-10:3 9:4-49
# ./src/components/atoms/button/stories.js
babel.config.js
module.exports = {
presets: ["#babel/preset-env", "#babel/preset-react"],
plugins: [
[
"#dr.pogodin/babel-plugin-react-css-modules",
{
webpackHotModuleReloading: true,
autoResolveMultipleImports: true,
filetypes: {
".scss": {
syntax: "postcss-scss",
},
},
generateScopedName: "[name]__[local]___[hash:base64:5]",
},
],
],
};
webpack.config.js for css (partial code inlcuded)
{
test: /\.(css|sass|scss)$/,
exclude: /node_modules/,
use: [
isDev ? "style-loader" : MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
modules: {
auto: (resourcePath) =>
resourcePath.indexOf("assets/stylesheets") === -1,
localIdentName:"[name]__[local]___[hash:base64:5]",
},
sourceMap: true,
},
},
"sass-loader",
],
}
storybook/webpack.config.js file
const custom = require('../webpack.config.js');
module.exports = {
// stories: ['../src/components/**/*.stories.js'],
webpackFinal: (config) => {
return {
...config,
module: {
rules: custom.module.rules,
},
resolve: {
...config.resolve,
...custom.resolve,
}
};
},
};
I don't know what you have done with your configuration but you would define the config things inside .storybook/main.js. And for global style css is supposed to be included in preview.js file.
In short, you have to do the few things:
Remove your .storybook/config.js and add .storybook/main.js with following content:
const custom = require('../webpack.config.js');
module.exports = {
stories: [
'../src/**/stories.js', // The name should have a prefix for component name like `button.stories.js` instead of `stories.js` like you've done. As you renamed, you can remove this pattern
"../src/**/*.stories.#(js|jsx|ts|tsx)"
],
webpackFinal: (config) => {
return {
...config,
module: {
rules: custom.module.rules,
},
resolve: {
...config.resolve,
...custom.resolve,
}
};
},
};
Create the .storybook/preview.js to import your global style:
import "../src/assets/stylesheets/app.scss";
Some people have been running into problems a some scss preset when using Storybook 6.2.0 with Webpack 5. Instead of using a preset, I recommend configuring the Webpack config in main.js as mentioned above. Here's the relevant portion of a working Storybook Webpack config for Sass:
module: {
...config.module,
rules: [
...config.module.rules,
{
test: /\.(scss)$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: function () {
return [require('precss'), require('autoprefixer')];
},
},
},
},
{
loader: require.resolve('sass-loader'),
options: {
implementation: require('sass'),
},
},
],
},
],
},
I've written more about getting Storybook off the ground with Webpack 5 (and modifying the Storybook Webpack config) over here.
Another reason this might happen: if you are adding new components to your app and the path defined for your sass-loader does not match anymore.
E.g. if you have this in your .storybook/main.js:
webpackFinal: async config => {
// Add SASS support
// https://storybook.js.org/docs/configurations/custom-webpack-config/#examples
config.module.rules.push({
test: /\.scss$/,
use: [
"style-loader",
{
loader: "css-loader",
options: {
modules: {
compileType: "icss",
},
},
},
"sass-loader",
],
include: path.resolve(__dirname, "../"),
})
Update or completely remove the include path.

"ReferenceError: waitForElement is not defined" when testing react.js

I am testing with Jest and react-testing-library a component that is calling an async function. When I run the test I get the error ReferenceError: waitForElement is not defined
Following this instructions I have tried:
without the useBuiltinsoption in .babelrc, including #babel/polyfill at the top of the app.test.jsx file, , and without #babel/polyfill in the entry array in webpack.config.js. I get the error ReferenceError: waitForElement is not defined from the test run but the application compiles succesfully
with useBuiltIns: 'entry', including #babel/polyfill at the top of the app.test.jsx file, and without #babel/polyfill in the entry array in webpack.config.js . I get Cannot find module 'core-js/modules/es6.array.every' from 'app.test.jsx' and the application fails to compile.
with useBuiltIns: 'entry', NOT including #babel/polyfill at the top of the app.test.jsx file, and WITH #babel/polyfill in the entry array in webpack.config.js. I get the error ReferenceError: waitForElement is not defined from the test run and the application fails to compile.
Here is the code from case 1:
imports in app.test.jsx
import '#babel/polyfill';
import React from 'react';
import { render, fireEvent, cleanup } from 'react-testing-library';
import AppContainer from '../components/AppContainer';
test in app.test.jsx
test('State change', async () => {
const { debug, getByLabelText, getByTestId, getByText } = render(<AppContainer />);
fireEvent.change(getByLabelText('testfield'), { target: { value: 'Hello' } });
fireEvent.click(getByTestId('button'));
await waitForElement(() => getByText('return value'));
debug();
});
webpack.config.js
const HtmlWebPackPlugin = require('html-webpack-plugin');
module.exports = {
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
},
],
},
],
},
resolve: {
extensions: ['*', '.js', '.jsx'],
},
plugins: [
new HtmlWebPackPlugin({
template: './src/index.html',
filename: './index.html',
}),
],
};
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": [
[
"#babel/plugin-proposal-class-properties",
{
"loose": true
}
]
]
}
I am expecting the waitForElement function to be awaiting for the "return value" text to appear in a second textfield, and then the debug() function to print the page html code. Instead I get the above mentioned errors.
You have to import waitForElement from react-testing-library:
import { render, waitForElement } from 'react-testing-library'
There's no need to install dom-testing-library because RTL depends on it already.
Ok, I solved the problem. I was missing the dom-testing-library dependency.
Here is the working solution.
Install dom-testing library: npm install --save-dev dom-testing-library.
In app.test.jsximport waitForElement and #babel/polyfill:
import '#babel/polyfill';
import { waitForElement } from 'dom-testing-library';
The rest of the code is as in case 1 above.

React: ReferenceError: regeneratorRuntime is not defined

I am trying to use async and await in my react application.
onSubmit = async (model) => {
await this.setState({ data: model });
}
After adding the above code i get an error in my browser console.
ReferenceError: regeneratorRuntime is not defined
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": [
"#babel/plugin-proposal-class-properties"
],
"sourceMaps": "inline"
}
webpack.config.js
const path = require("path");
const WebpackShellPlugin = require("webpack-shell-plugin");
const nodeExternals = require("webpack-node-externals");
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = [
{
Server config removed
},
{
entry: {
app1: './src/public/app1/index.js',
app2: './src/public/app2/index.js',
app3: './src/public/app3/index.js',
},
devtool: "source-map",
output: {
path: __dirname + '/dist/public/',
publicPath: '/',
filename: '[name]/bundle.js',
devtoolLineToLine: true,
sourceMapFilename: "[name]/bundle.js.map",
},
module: {
rules: [
{
test: /(\.css|.scss)$/,
use: [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "sass-loader" // compiles Sass to CSS
}]
},
{
test: /\.(jsx|js)?$/,
use: [{
loader: "babel-loader",
// options: {
// cacheDirectory: true,
// presets: ['react', 'es2015'] // Transpiles JSX and ES6
// }
}]
}
],
},
"plugins": [
new CopyWebpackPlugin([
{
from: 'src/public/app1/index.html',
to: 'app1'
},
{
from: 'src/public/app2/index.html',
to: 'app2'
},
{
from: 'src/public/app3/index.html',
to: 'app3'
},
]),
]
}
];
I have added my babelrc and webpack config. Please let me know if i am missing something that would cause this error to appear in my browser console.
Import regeneratorRuntime in the component using async/await:
import regeneratorRuntime from "regenerator-runtime";
*** UPDATED ANSWER *** (probably don't use above)
Import babel and #babel/plugin-transform-runtime plugin:
package.json
"devDependencies": {
"#babel/core": "^7.8.7",
"#babel/plugin-transform-runtime": "^7.8.3",
},
.babelrc
{
"plugins": ["#babel/plugin-transform-runtime"]
}
You did not include your package.json file, so it is a bit unclear what you are missing.
Assuming you have #babel/polyfill as a dependency in your package.json file, is it possible that you are not specifying:
import '#babel/polyfill'
in your React file (such as index.js)?
Adding polyfills from create-react-app worked for me.
yarn add --dev react-app-polyfill
Then add the following lines to webpack.config.js
entry: {
app: [
'react-app-polyfill/ie9', // Only if you want to support IE 9
'react-app-polyfill/stable',
'./src/index.jsx',
],
},
See more examples on the react-app-polyfill GitHub page.

mocha-webpack compile with Cannot read property 'babel' of undefined

Webpack compilation error when unit testing. I try to modify the test file but still so, it should be webpack configuration problems, test the error component error
Webpack compilation error when unit testing. I try to modify the test file but still so, it should be webpack configuration problems, test the error component error
webpack.test.config.js
const path = require('path');
const config = {
entry: {
vendor: ["babel-polyfill", "react", "react-dom"],
app: './index.js'
},
resolve: {
alias: {
'fonts': path.resolve(__dirname, 'public/fonts/'),
'#components': path.resolve(__dirname, 'src/components/'),
'#services': path.resolve(__dirname, 'src/services/'),
'#routes': path.resolve(__dirname, 'src/routes/'),
'#utils': path.resolve(__dirname, 'src/utils/'),
'#less': path.resolve(__dirname, 'src/less/'),
'#images': path.resolve(__dirname, 'public/images/'),
'#public': path.resolve(__dirname, 'public/'),
}
},
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0']
}
}, {
test: /\.less$/,
exclude: /node_modules/,
loader: 'style-loader!css-loader!less-loader'
}]
}
};
module.exports = config;
Agent.spec.js
import React from 'react';
import { expect } from 'chai';
import { shallow } from 'enzyme';
import Agent from '#components/agent/index';
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
describe('<Agent />', () => {
it('Agent renderning', function () {
let app = shallow(<Agent/>);
expect(app.find('button').exists());
});
});
the error
WEBPACK Failed to compile with 1 error(s)
Error in ./test/unit/specs/Agent.spec.js
TypeError: Cannot read property 'babel' of undefined
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! # unit: `mocha-webpack --recursive test/unit/specs/*.js --webpack-config webpack.test.config.js`
npm ERR! Exit status 1

React, Babel, Webpack not parsing jsx, unexpected token error [duplicate]

This question already has answers here:
babel-loader jsx SyntaxError: Unexpected token [duplicate]
(8 answers)
Closed 6 years ago.
I am trying to build my app using wepback and getting getting stuck at this unexpected token error. All the dependencies for my project are fine and upto date I am using the same project somewhere else and it is building fine but when I try to build my current code which is same it gives the error, below are config.js and error descriptions
Here is my app.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import {Router} from 'react-router';
import Routes from '../routes/routes';
import injectTapEventPlugin from 'react-tap-event-plugin';
import { browserHistory } from 'react-router';
require('../Config');
injectTapEventPlugin();
window.EventEmitter = {
_events: {},
dispatch: function (event, data, returnFirstResult) {
if (!this._events[event]) return;
for (var i = 0; i < this._events[event].length; i++)
{
if(this._events[event][i])
{
var r = this._events[event][i](data);
if(returnFirstResult)
return r;
}
}
},
subscribe: function (event, callback, onlyOne) {
if (!this._events[event] || onlyOne) this._events[event] = []; // new event
this._events[event].push(callback);
}
};
// Render the main app react component into the app div.
// For more details see: https://facebook.github.io/react/docs/top-level-api.html#react.render
ReactDOM.render(<Router history={browserHistory}>{Routes}</Router>, document.getElementById('app'));
Here is my config.js
var webpack = require('webpack');
var path = require('path');
var buildPath = path.resolve(__dirname, '../project/public/js/');
var nodeModulesPath = path.resolve(__dirname, 'node_modules');
var TransferWebpackPlugin = require('transfer-webpack-plugin');
var config = {
entry: {
app: path.join(__dirname, '/app/entry_points/app.jsx'),
vendor: ['react', 'radium'],
},
resolve: {
extensions: ["", ".js", ".jsx"]
},
devtool: 'source-map',
output: {
path: buildPath,
publicPath: '/js/',
filename: 'mobile.[name].js'
},
plugins: [
new webpack.optimize.CommonsChunkPlugin("vendor", "mobile.vendor.js"),
new webpack.DefinePlugin({}),
new webpack.NoErrorsPlugin(),
],
module: {
preLoaders: [
{
test: /\.(js|jsx)$/,
loader: 'eslint-loader',
include: [path.resolve(__dirname, "src/app")],
exclude: [nodeModulesPath]
},
],
loaders: [
{
test: /\.(js|jsx)$/,
loaders: [
'babel-loader'
],
exclude: [nodeModulesPath]
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
]
},
eslint: {
configFile: '.eslintrc'
},
};
module.exports = config;
This is the error I get when I try to build:
ERROR in ./app/entry_points/app.jsx
Module build failed: SyntaxError: /home/zeus/Glide/project/project-mobile/app/entry_points/app.jsx: Unexpected token (46:16)
44 | // Render the main app react component into the app div.
45 | // For more details see: https://facebook.github.io/react/docs/top-level-api.html#react.render
> 46 | ReactDOM.render(<Router history={browserHistory}>{Routes}</Router>, document.getElementById('app'));
| ^
I am using react v0.14.8, react-dom v0.14.8, babel-loader ^6.2.1
i believe you need to specify the presets with babel and install the npm module babel-preset-react
loaders: [
{
test: /\.(js|jsx)$/,
loaders: [
'babel-loader'
],
exclude: [nodeModulesPath],
query: {
presets: ['react']
}
},
...
]
you'd also want to add es2015 to that presets array if you're using it.

Resources