[react-testing-library] 유저 이벤트
글 작성자: 망고좋아
반응형

🎯 유저 이벤트
📝 user-event
- 내장 이벤트 함수인 fireEvent, createEvent를 좀 더 직관적이고 범용적으로 사용할 수 있도록 만든 라이브러리
- click, type, keyboard, upload, hover, tab 등 유저가 실제로 웹페이지를 사용하며 만드는 이벤트를 메서드로 제공한다.
📝 user-event - click
import userEvent from "@testing-library/user-event"; import { render } from "@testing-library/react"; userEvent.click(submitButton) userEvent.click(submitButton, { shiftKey: true }) userEvent.click(submitButton, { shiftKey: true }, { clickCount: 5 }) test('숨은 텍스트를 보여준다.', () => { const text = "Hidden text!"; const { getByRole, queryByText } = render(<Expansion text={text} />); expect(queryByText("Hidden text!")).toBe(null); const showButton = getByRole("button", { name: "Expand" }); expect(showButton).toBeInTheDocument(); userEvent.click(showButton); expect(queryByText(text)).toBeInTheDocument(); })
- 먼저 테스트 코드를 작성해준다.
function Expansion({ text }) { const [expanded, setExpanded] = useState(false); return ( <div> <button onClick={() => setExpanded((b) => !b)}>Expand</button> {expanded && <div>{text}</div>} </div> ); }
- 테스트 코드를 기반으로 컴포넌트 코드 작성
📝 user-event - type
import userEvent from "@testing-library/user-event"; import { render } from "@testing-library/react"; userEvent.type(inputElement, 'react advanced') userEvent.type(inputElement, 'react{space}advanced{enter}') await userEvent.type(inputElement, 'react advanced', { delay: 300 }) test("Typeahead에서 쿼리에 따른 검색 결과를 보인다", () => { const mockSearchData = ["kim", "song", "shim", "park", "yoon"]; const { getByPlaceholderText, getAllByRole } = render( <Typeahead searchData={mockSearchData} /> ); const inputElement = getByPlaceholderText("Type name..."); userEvent.type(inputElement, "s"); // s 입력 expect(getAllByRole("listitem").length).toBe(2); // 2개의 결과가 나온다면 userEvent.clear(inputElement); expect(getAllByRole("listitem").length).toBe(mockSearchData.length); });
userEvent.type()
을 이용하면 타이핑, 즉 값을 입력할 수 있다.
반응형
'프로그래밍 > testing' 카테고리의 다른 글
[react-testing-library] 테스트 코드 작성 시 Tip (0) | 2022.03.02 |
---|---|
[react-testing-library] 쿼리의 우선순위 (0) | 2022.01.17 |
[react-testing-library] react-testing-library란? (0) | 2022.01.17 |
[Jest] Async assertion (0) | 2022.01.17 |
[Jest] Assertion Matchers 활용 (0) | 2022.01.17 |
댓글
이 글 공유하기
다른 글
-
[react-testing-library] 테스트 코드 작성 시 Tip
[react-testing-library] 테스트 코드 작성 시 Tip
2022.03.02 -
[react-testing-library] 쿼리의 우선순위
[react-testing-library] 쿼리의 우선순위
2022.01.17 -
[react-testing-library] react-testing-library란?
[react-testing-library] react-testing-library란?
2022.01.17🎯 react-testing-library 테스트가 소프트웨어가 사용되는 모습을 닮을수록, 테스트를 더욱 신뢰할 수 있게 된다. The more your tests resemble the way your software is used, the more confidence they can give you. 사용되는 모습이란? 사용자가 직접 앱을 사용하는 모습이다. React 컴포넌트의 특정 메서드나 상태를 테스트하는 게 아니라, 실제 유저가 사용하는 방식대로 테스트하는 접근하는 것이다. 유저가 페이지에서 어떤 DOM 요소에 접근하는 방법을 흉내 낸다. 이 방식으로 테스트 코드를 작성하면, 내부 구현이 바뀌어도 테스트가 깨지지 않는다. React 컴포넌트가 렌더링 한 결과에 대한 접근만 가능하다. 결과 중심… -
[Jest] Async assertion
[Jest] Async assertion
2022.01.17🎯 Async assertion callback 패턴의 경우 test() 함수가 제공하는 done() 함수를 활용하여 콜백이 끝나고 done()을 호출이 된다. 에러가 발생하면 done()의 인자로 에러를 넘긴다. Promise 패턴의 경우 async/await을 활용하거나 Promise를 리턴한다. function isPythagoreanAsync(a, b, c) { return new Promise(resolve => { setTimeout(() => { const result = isPythagorean(a, b, c) if (result) return resolve(result) reject(new Error("Not pythagorean")) }, 500) }) } test('Should 3, …
댓글을 사용할 수 없습니다.