Jest | [에러 해결] ReactDOM.render no longer supported in React 18

Kate Jung·2022년 4월 12일
1

Front-end Test

목록 보기
7/17
post-thumbnail

💬 에러 메세지

Warning: ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it's running React 17. Learn more: https://reactjs.org/link/switch-to-createroot

📌 해결 방법

1. react testing library의 버전 업데이트

패키지 버전 13.0.0은 새 createRootAPI에 대한 지원을 추가함.

  • 프로젝트의 루트 디렉터리에서 터미널을 열고 다음 명령을 실행
    npm install --save-dev @testing-library/react@latest
    
    npm install --save-dev @testing-library/jest-dom@latest
    
    npm install --save-dev @testing-library/user-event@latest
  • 사용 중인 모든 react testing library 패키지의 버전을 업데이트해야 함.

2. index.js 에 새 createRootAPI 적용

index.js 파일은 새 createRootAPI를 사용하여 애플리케이션을 렌더링해야 함.

  • index.js
    import {StrictMode} from 'react';
    import {createRoot} from 'react-dom/client';
    
    import App from './App';
    
    // 👇️ IMPORTANT: div ID has to match with index.html
    const rootElement = document.getElementById('root');
    const root = createRoot(rootElement);
    
    // 👇️ if you use TypeScript, add non-null (!) assertion operator
    // const root = createRoot(rootElement!);
    
    root.render(
      <StrictMode>
        <App />
      </StrictMode>,
    );

3. 오류 없이 테스트 시작 가능

  • App.test.js
    import {render, screen} from '@testing-library/react';
    import App from './App';
    
    test('renders react component', () => {
      render(<App />);
      const divElement = screen.getByText(/hello world/i);
      expect(divElement).toBeInTheDocument();
    });

참고

profile
복습 목적 블로그 입니다.

0개의 댓글