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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With