[javascript] Enzyme의 셀렉터 사용법

Enzyme은 React 컴포넌트의 테스트를 위한 JavaScript 라이브러리입니다. Enzyme은 테스트 작성을 더욱 간편하게 만들어주는 다양한 유틸리티 함수와 셀렉터를 제공합니다. 이번 글에서는 Enzyme의 셀렉터를 사용하는 방법을 살펴보겠습니다.

설치

Enzyme을 사용하기 위해서는 먼저 패키지를 설치해야 합니다. npm을 사용하여 다음과 같이 설치할 수 있습니다.

npm install --save enzyme enzyme-adapter-react-16 react-test-renderer

셀렉터 사용법

find()

Enzyme의 find() 함수는 특정 조건에 맞는 React 컴포넌트들을 찾을 때 사용됩니다. find() 함수는 CSS 선택자와 비슷한 방식으로 요소를 찾을 수 있습니다.

예를 들어, 다음과 같은 React 컴포넌트가 있다고 가정해봅시다.

import React from 'react';

function MyComponent() {
  return (
    <div>
      <h1>Hello, World!</h1>
      <p>This is a paragraph.</p>
    </div>
  );
}

이 컴포넌트에서 특정 요소를 찾기 위해 다음과 같이 find() 함수를 사용할 수 있습니다.

import { shallow } from 'enzyme';

test('find() function usage', () => {
  const wrapper = shallow(<MyComponent />);

  const h1 = wrapper.find('h1');
  const p = wrapper.find('p');

  expect(h1.text()).toBe('Hello, World!');
  expect(p.text()).toBe('This is a paragraph.');
});

first()와 last()

Enzyme의 first()last() 함수는 선택된 요소들 중 첫 번째와 마지막 요소를 반환합니다. 예를 들어, 다음과 같이 사용할 수 있습니다.

import { shallow } from 'enzyme';

test('first() and last() function usage', () => {
  const wrapper = shallow(<MyComponent />);

  const firstChild = wrapper.find('div').children().first();
  const lastChild = wrapper.find('div').children().last();

  expect(firstChild.is('h1')).toBe(true);
  expect(lastChild.is('p')).toBe(true);
});

filter()

Enzyme의 filter() 함수는 선택된 요소들 중 특정 조건에 맞는 요소들만을 반환합니다.

import { shallow } from 'enzyme';

test('filter() function usage', () => {
  const wrapper = shallow(<MyComponent />);

  const h1 = wrapper.find('div').children().filter('h1');
  const p = wrapper.find('div').children().filter('p');

  expect(h1.text()).toBe('Hello, World!');
  expect(p.text()).toBe('This is a paragraph.');
});

마무리

Enzyme의 셀렉터를 사용하면 React 컴포넌트의 테스트를 더욱 효율적으로 작성할 수 있습니다. find(), first(), last(), filter() 함수를 잘 활용하여 테스트를 작성해보세요.

더 자세한 내용은 Enzyme 공식 문서를 참고하시기 바랍니다.