[TDD] jest에서 createRoot 사용방법

dev stefanCho·2022년 11월 12일
0

tdd

목록 보기
4/4

React 17 버전까지는 render 함수를 사용하였습니다.
아래와 같이 test를 작성하면 DOM이 정상적으로 교체되었습니다.

// src/Appointment.js
import React from 'react';

const Appointment = ({ customer }) => {
  return <div>{customer.firstName}</div>;
};

export default Appointment;
// test/Appointment.test.js
import React from 'react';
import { render } from 'react-dom';
import Appointment from '../src/Appointment';

describe('Appointment', () => {
  it('render..', () => {
    const customer = { firstName: 'Ashley' };
    const component = <Appointment customer={customer} />;
    const container = document.createElement('div');
    document.body.appendChild(container);
    render(component, container);
    expect(document.body.textContent).toMatch('Ashley'); // test 성공
  });
});

React 18 부터는 createRoot를 사용해야 합니다.
다만 이때는 act 함수도 함께 사용해주어야 정상적으로 dom이 교체가 됩니다.

// test/Appointment.test.js
import React from 'react';
import { createRoot } from 'react-dom/client';
import { act } from 'react-dom/test-utils';
import Appointment from '../src/Appointment';

describe('Appointment', () => {
  it('render..', () => {
    const customer = { firstName: 'Ashley' };
    const component = <Appointment customer={customer} />;
    const container = document.createElement('div');
    document.body.appendChild(container);
    const root = createRoot(container);
    act(() => root.render(component));
    expect(document.body.textContent).toMatch('Ashley');  // test 성공
  });
});

act 함수가 동작하기 위해서는 package.json의 jest 설정에서 IS_REACT_ACT_ENVIRONMENT도 추가해야 합니다.

  "jest": {
    "testEnvironment": "jsdom",
    "globals": {
      "IS_REACT_ACT_ENVIRONMENT": true
    }
  }

Ref

profile
Front-end Developer

0개의 댓글