I tried writing a test for this file but received the error Target container is not a DOM element. All the needed files were imported.
const rootElement = document.getElementById('root');
ReactDOM.render(
<AppRoot>
<BrowserRouter>
<title className='myAppTitle' id="myApp">MY APP</title>
<div data-testId="index">
<Routes>
<Route path="/*" element={ <App /> } />
</Routes>
</div>
</BrowserRouter>
</AppRoot>
,
rootElement,
);
This is the jest test I tried. I expected the test to pass. I imported all the needed imports but the test is failing at .render(). The error says Target container is not a DOM element. Is there a way to get test coverage for an index.js file of a react app?
describe('index', () => {
jest.mock('react-dom', ()=> ({render: jest.fn()}))
const root = document.createElement('div');
beforeEach(() => {
document.body.appendChild(root);
})
it('should render without crashing', async () => {
const rootElement = document.getElementById('root');
ReactDOM.render(
<AppRoot>
<BrowserRouter>
<title className='myapptitle' id="myapp">MY APP</title>
<div data-testId="index">
<Routes>
<Route path="/*" element={ <App /> } />
</Routes>
</div>
</BrowserRouter>
</AppRoot>
,
rootElement,
);
expect(title).toBe('My App');
expect(document.getElementById('myApp')).toBeTruthy();
});
})