'Jest fails because Target container is not a DOM element
I am trying to run component test on React app with jest and failing with below error. But the application is working fine normally
FAIL src/__tests__/app.test.tsx
● Test suite failed to run
Target container is not a DOM element.
7 | import reportWebVitals from './reportWebVitals';
8 |
> 9 | ReactDOM.render(
| ^
10 | <React.StrictMode>
11 | <Provider store={store}>
12 | <App />
at Object.render (node_modules/react-dom/cjs/react-dom.development.js:26091:13)
at Object.<anonymous> (src/index.tsx:9:10)
at Object.<anonymous> (src/App.tsx:6:1)
at Object.<anonymous> (src/__tests__/app.test.tsx:45:1)
Here is my App.tsx file.
import React from 'react';
import 'reflect-metadata';
import { BrowserRouter, Switch } from 'react-router-dom';
import { Message } from '@library/queues';
const App: React.FC = () => {
return (
<ThemeProvider theme={'dark'}>
// routes
</ThemeProvider>
)}
export default App;
Here is index file
import React from 'react';
import ReactDOM from 'react-dom';
import './index.scss';
import App from 'App';
import { Provider } from 'react-redux';
import store from 'redux/store';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root'),
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
reportWebVitals();
and finally the test file
import React from 'react';
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
I have verified many links and tried different ways but all leads to this error only. I am using one private npm module and mapped that using moduleNameMappers
and sometimes that also throws error.
moduleNameMapper: {
'^@library/queues(.*)$': '<rootDir>/src/$1', -- working without errors but throwing errors when we run tests
// '^@library/queues(.*)$': '<rootDir>/node_modules/$1', -- throwing errors
'\\.(css|scss|jpg|png)$': '<rootDir>/empty-mock-module.js',
},
Could somebody helps me whether I'm doing correct or not. I need to know how to map node_modules libraries in code. All the npm modules are working except my private module.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|