Categories
Development

jest failing with “Target container is not a DOM element.” cause it tests my index.tsx

So i want to set up testing on a react project i working on.

i set up some test files, but jest always fails with

Test suite failed to run

    Target container is not a DOM element.

      4 | import App from '~/App';
      5 |
    > 6 | ReactDOM.render(<App />, document.getElementById('root'));
        |          ^
      7 |

I tested this with multiple test files. Even if i test a component deep into my components folder i get the same error. I read on an other issue that this can happen if i also render my app in the same file i declare it.
But i have a seperate index.tsx that is only for rendering. So i don’t get why jest is try to testing my index.tsx.

// file structure

root/
   - src/
      - components/
      - App.tsx
      - App.test.tsx
      - index.tsx
   - jest.config.js       
// jest.config.js
module.exports = {

  roots: ['<rootDir>/src'],
  transform: {
    '^.+\\.tsx?$': 'ts-jest'
  },
  moduleNameMapper: {
    '~/*': '<rootDir>/src'
  },
  setupFilesAfterEnv: ['@testing-library/jest-dom/extend-expect'],

  testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',

  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node']
};

// App.tsx

import * as React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import styled, { ThemeProvider } from 'styled-components';

// [...]
export const DMSContext = React.createContext(dmsContextValue);

export const StyledApp = styled.div`
  display: flex;
`;

const App: React.FC = (): React.ReactElement => {
// [...]
  return (
    <Router>
      <DMSContext.Provider value={dmsContextValue}>
        <ThemeProvider theme={theme}>
          <>
            <GlobalStyles />
            <StyledApp>
              <Burger onClickHandler={toggleSideBar} mobileView={mobileView} expanded={expanded} />
              <SideNav
                mobileView={mobileView}
                expanded={expanded || !mobileView}
                onLinkClick={(): void => setExpanded(false)}
              />
              <Switch>
                // [...Routes]
              </Switch>
            </StyledApp>
          </>
        </ThemeProvider>
      </DMSContext.Provider>
    </Router>
  );
};

export default App;
// App.test.tsx
import * as React from 'react';
import { render } from '@testing-library/react';
import App from './App';
import '@testing-library/jest-dom/extend-expect';

describe('<App />', () => {
  test('should render the app', async () => {
    const { getByText } = render(<App />);
    expect(getByText('Projects')).toBeInTheDocument();
  });
});

Leave a Reply

Your email address will not be published. Required fields are marked *