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

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.

Related

Cannot find module error while import using jest in next.js

I am trying to configure Jest in my Next.js project. In my test file, I have imported my component like import { HamburgerMenu } from './HamburgerMenu.jsx'. In that component, there are so many other imports. Once of them is
import {
checkValidEmail, getNumbers, getFormttedPhoneNo, validateSubscription,
} from 'helpers/utils';
When I run tests, it gives me the following error (which is on above import statement):
Cannot find module 'helpers/utils' from 'components/common/Smart/HamburgerMenu/HamburgerMenu.jsx'
So here are the details.
jest.config.js (at root dir)
module.exports = {
collectCoverageFrom: [
'**/*.{js,jsx,ts,tsx}',
'!**/*.d.ts',
'!**/node_modules/**',
],
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
testPathIgnorePatterns: ['/node_modules/', '/.next/'],
transform: {
'^.+\\.(js|jsx|ts|tsx)$': '<rootDir>/node_modules/babel-jest'
},
transformIgnorePatterns: [
'/node_modules/',
'^.+\\.module\\.(css|sass|scss)$',
],
moduleNameMapper: {
'^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
},
}
I have added jest: true in the ESLint file.
babel.config.js file (at root dir):
module.exports = {
presets: ["next/babel"],
plugins: [["babel-plugin-styled-components", { ssr: true }]]
};
You can try to add
...
moduleDirectories: ['node_modules', '.'],
...
to your jest.config.js

Moment is not defined when using React with Webpack

I'm in the progress of "Reactifying" a PHP application and am adding a single component to start (with several child components). In addition to the custom components, there are several library dependencies (react-bootstrap, moment, etc).
I'm using webpack to compile it and it compiles correctly and generates the dist/main.js as expected. However, when adding it to the HTML template I get the error "moment is not defined", though the "react-bootstrap" dependencies appear to load correctly. Based on the guidance in https://github.com/palantir/blueprint/issues/959, I tried both import * as moment from 'moment', import moment from 'moment' as well as the const moment = require('moment'); I had previously been using which compiled fine with browserify.
webpack.config.js
const path = require('path')
module.exports = {
mode: 'development',
context: path.resolve(__dirname, 'components'),
entry: './dir/EntryComponent.app.jsx',
resolve: {
extensions: ['.jsx', '.json', '.js']
},
optimization: {
minimize: false
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
}
};
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
Component.jsx
import Collapse from "react-bootstrap/Collapse";
import moment from 'moment';
const Datetime = require('react-datetime');
...
<label>Start</label>
<Datetime
value={this.props.startDate}
placeholder="Start Date"
dateFormat='YYYY-MM-DD'
timeFormat={false}
input={true}
viewDate={moment().subtract(1, 'month')}
onChange={date => this.props.updateStartDate(date)}
closeOnSelect={true}
closeOnTab={true}
viewMode="months"
inputProps={{readonly: 'readonly'}}/>

Test with enzyme: Unexpected token in mount()

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

Module not found: Error: Can't resolve './component/Hello'

I´m trying to import a simple Component but the webpack seems to cant find it. The route is good and the "resolve" in the webpack config is great too, therefore I cant understand where is the issue.
Give it at look please.
By the way, its a Sails/React environment.
ERROR in ./assets/src/component/Hello.jsx 6:12
Module parse failed: Unexpected token (6:12)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.
Hello.jsx:
import React from 'react'
class Hello extends React.Component {
render() {
return(
<div> // Err supposed to be here (line6)
Hello World!
</div>
)
}
}
export default Hello;
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import Hello from './component/Hello'
const App = () => {
return (
<div>
Simple Sails-React stater
<Hello/>
</div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
.babelrc:
{
"presets": ["#babel/env", "#babel/react"]
}
webpack config file:
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
entry: './assets/src/index.js'
},
output: {
path: __dirname + '/.tmp/public',
filename: 'bundle.js'
},
module: {
rules: [
{
use: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
},
{
use: ['style-loader', 'css-loader'],
test: /\.css$/
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
plugins: [
new HtmlWebpackPlugin({
template: 'assets/src/index.html'
})
]
};
the structure is like this:
-src
--component
----Hello.jsx
--index.js
--index.html
Could you try change extension to Hello.js or change bable-loader test to
test: /\.(js|jsx)$/,

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.

Resources