테스팅 소개
Cloudscape 컴포넌트와 상호작용하며 애플리케이션을 테스트할 수 있는 방법을 소개해요. 컴포넌트마다 안정적이고 프레임워크에 구애받지 않는 API를 제공하는 테스트 유틸리티를 사용해, 선택자(CSS 셀렉터)를 신경 쓰지 않고 컴포넌트의 관련 부분에 접근할 수 있답니다.
출처: 문서
본문
소개
애플리케이션에 대한 자동화 테스트를 만들 때 Cloudscape 컴포넌트와 상호작용하게 됩니다. 예를 들어 Cloudscape button을 선택하고 애플리케이션이 버튼의 onClick 동작을 반영하도록 업데이트되었는지 단언합니다.
Cloudscape 컴포넌트의 내부 HTML 구조(CSS 클래스 이름 포함)는 언제든지 변경될 수 있어요. 그래서 각 컴포넌트에 대해 테스트 유틸리티를 만들었습니다. 테스트 유틸리티는 어떤 선택자를 사용할지 고민하지 않고 컴포넌트의 관련 부분에 접근할 수 있게 해주는 안정적이고 프레임워크에 구애받지 않는 API를 노출합니다.
Cloudscape는 두 가지 테스트 유틸리티 세트를 제공합니다:
DOM 유틸리티
DOM에 직접 접근할 수 있을 때 Cloudscape 컴포넌트와 상호작용할 수 있게 하는 유틸리티 세트예요. DOM 유틸리티는 주로 단위 테스트에서 Cloudscape 컴포넌트를 쿼리하고 제공된 유틸리티로 상호작용하는 데 사용됩니다. 예:
import createWrapper from "@cloudscape-design/components/test-utils/dom";
import { render } from "@testing-library/react";
describe("<Button/>", () => {
it("clicks the submit button", () => {
const { container } = render(<Component />);
const wrapper = createWrapper(container);
const buttonWrapper = wrapper.findButton();
buttonWrapper.click() // clicks the button element
// rest of your test logic
});
선택자 유틸리티
CSS 선택자 문자열로 Cloudscape 컴포넌트를 찾을 수 있게 하는 유틸리티 세트예요. 선택자 유틸리티는 주로 엔드투엔드 및 통합 테스트에 사용됩니다.
import createWrapper from "@cloudscape-design/components/test-utils/selectors";
/**
* browser - is a global object representing your testing framework.
* The exact API could be different for your stack.
*/
describe("Button", () => {
it("clicks the submit button", async () => {
await browser.url("your-test-page");
const wrapper = createWrapper();
const buttonSelector = wrapper
.findButton('[data-testid="submit-button"]')
.toSelector(); // string selector
await browser.$(buttonSelector).click();
// rest of your test
});
});
DOM 유틸리티와 달리 click이나 focus 같은 유틸리티를 제공하지 않는다는 점에 유의하세요. 선택자 유틸리티는 환경의 브라우저 API로 상호작용할 수 있는 해당 CSS 선택자를 반환하기 때문입니다.
더 많은 예제 찾기
일부 복잡한 컴포넌트의 경우 컴포넌트 페이지의 테스팅 탭에서 테스트 유틸리티를 사용한 더 정교한 코드 예제를 찾을 수 있어요. 몇 가지 예:
Cloudscape 컴포넌트 쿼리하기
요소를 찾는 데 사용할 수 있는 주요 유틸리티 유형은 다음과 같습니다:
- 컴포넌트별 find 유틸리티: 각 Cloudscape 컴포넌트에는 해당하는
findX유틸리티가 있어요(예:findButton(...)). - 컴포넌트별 findAll 유틸리티: 각 Cloudscape 컴포넌트에는 해당하는
findAllX유틸리티도 있습니다(예:findAllButtons(...)). - 일반 find 유틸리티:
find(...)로 단일 요소를 찾고findAll(...)로 여러 요소를 찾을 수 있으며, 둘 다 일반 선택에 사용됩니다. - 컴포넌트별 findClosest 유틸리티: 각 Cloudscape 컴포넌트에는 해당 컴포넌트의 인스턴스인 가장 가까운 부모를 찾는
findClosestX유틸리티도 있습니다(예:findClosestContainer()). 이 유틸리티는 단위 테스트에서 사용할 수 있지만 통합 테스트에서는 사용할 수 없습니다.
findX, findAllX, find 유틸리티는 문자열을 인수로 받습니다. 문자열은 클래스 이름이나 ID 같은 표준 CSS 선택자 또는 [data-testid="test-id"] 같은 사용자 정의 데이터 속성일 수 있어요.
데이터 속성 사용하기
데이터 속성을 사용해 컴포넌트를 선택하거나 쿼리하는 것을 권장합니다. 테스트를 UI의 스타일링과 구조와 분리해 UI 변경에 더 견고하게 만들기 때문입니다. 또한 data-testid 같은 속성은 리팩토링 중에도 더 안정적이고 변경될 가능성이 적어, 클래스 이름이나 ID보다 더 신뢰할 수 있는 선택자를 제공합니다.
단위 테스트 예제
import createWrapper from '@cloudscape-design/components/test-utils/dom';
import { render } from '@testing-library/react';
const Component = () => <Button data-testid="submit-button">Submit</Button>;
it('clicks the submit button', () => {
const { container } = render(<Component />);
const wrapper = createWrapper().findButton('[data-testid="submit-button"]');
wrapper.click(); // Clicks the button using the stable data-testid attribute
});
통합 테스트 예제
import createWrapper from '@cloudscape-design/components/test-utils/selectors';
/**
* browser - is a global object representing your testing framework.
* The exact API could be different for your stack.
*/
it('clicks the submit button', async () => {
const wrapper = createWrapper().findButton('[data-testid="submit-button"]');
await browser.url('your-test-page');
await browser.$(wrapper.toSelector()).click();
});
findAll 유틸리티 사용하기
findAll 유틸리티는 여러 컴포넌트 인스턴스와 상호작용하거나 검증해야 할 때 유용합니다. 이 메서드는 래퍼 객체의 배열을 반환해 여러 요소에 대한 동작이나 단언을 수행할 수 있게 합니다.
import createWrapper from '@cloudscape-design/components/test-utils/dom';
import { render } from '@testing-library/react';
import Button from '@cloudscape-design/components/button';
const Component = () => (
<>
<Button>First</Button>
<Button>Second</Button>
<Button>Third</Button>
</>
);
it('finds and interacts with multiple buttons', () => {
const { container } = render(<Component />);
const wrapper = createWrapper(container);
const buttons = wrapper.findAllButtons();
expect(buttons.length).toBe(3);
expect(buttons[0].getElement().textContent).toBe('First');
expect(buttons[1].getElement().textContent).toBe('Second');
expect(buttons[2].getElement().textContent).toBe('Third');
buttons.forEach(button => button.click());
});
테스트에서 선택적 체이닝(optionsal chaining)을 사용하지 마세요
다음 예제를 고려하세요:
import createWrapper from '@cloudscape-design/components/test-utils/dom';
const Component = () => <Button data-testid="button1">Test Button</Button>;
// ❌ this approach can hide errors:
it('clicks a button', () => {
createWrapper().findButton('[data-testid="button-1-2"]')?.click();
// rest of your test
});
위 코드의 문제는 선택적 체이닝( ?.)이 선택된 요소를 찾지 못하면 오류를 억제해 테스트가 잘못 통과할 수 있다는 것이에요. 이는 테스트가 기대 동작을 제대로 검증하지 못하게 할 수 있습니다.
대신 선택적 체이닝을 피해 요소를 찾지 못하면 테스트가 실패하도록 하는 것이 좋습니다:
// ✅ recommended approach:
it('clicks a button', () => {
const wrapper = createWrapper().findButton('[data-testid="button-1"]');
wrapper!.click();
// this will throw an error if the button is not found, which ensures the test fails correctly
});
컴포넌트의 내부 구현에 의존하지 마세요
Cloudscape 컴포넌트를 쿼리할 때 내부 클래스 이름이나 구조를 사용하는 것을 피하는 것이 중요해요. 변경되어 테스트가 깨질 수 있기 때문입니다. 대신 data-testid 속성 같은 더 안정적인 선택자를 사용하거나 보이는 텍스트에 의존하세요.
import React from 'react';
import { render, screen } from '@testing-library/react';
import createWrapper from '@cloudscape-design/components/test-utils/dom';
import Button from '@cloudscape-design/components/button';
import '@testing-library/jest-dom';
const Component = () => <Button data-testid="test-button">Test</Button>;
it('test button text', () => {
const { container } = render(<Component />);
const wrapper = createWrapper(container);
// ❌ avoid using an internal class name as a selector
expect(wrapper.findButton('[class*="awsui_button_123"]')!.getElement().textContent).toContain('Test');
// ❌ avoid using find and findAll with internal class names
expect(wrapper.find('.awsui__button_123')!.getElement().textContent).toContain('Test');
expect(wrapper.findAll('[class*=awsui_]').length).toEqual(2);
// ✅ prefer querying using the data attributes
expect(wrapper.findButton('[data-testid="test-button"]')!.getElement().textContent).toContain('Test');
// ✅ or querying by on screen text
expect(screen.getByText('Test')).toBeInTheDocument();
});