This post is what I took notes from the React Testing for Beginners By Programming with Mosh.
What to test
Testing Components
- How they render
- How they responsd to user actions
No tests > Bad tests
Bad tests are worse than No tests.
Poorly written tests can get in the way and slow us down.
Test the behaviour (What the application does), not the implementation (How it's implemented)
Integration Tests might be slower than unit test, because of writing several unit tests together.
But it gives us better confidence that the application works.
Tests are less likely to break, if we refactor as long as the end result stays the same!
getByRole VS getByText
`getByRole`
semantic tags <button>, <heading>
`getByText`
tags not having roles <div>, <p>
getBy... VS queryBy...
`getBy...` throws an error if there's no element in the DOM.
it('should not render edit button if user is NOT admin', () => {
const user = {
id: 1,
name: 'hana',
isAdmin: false,
};
render(<UserAccount user={user} />);
const button = screen.queryByRole('button', { name: /edit/i });
expect(button).not.toBeInTheDocument();
});
`queryBy...` returns the matching node, and return `null` if no elements match.
queryByRole is more appropriate if I want to see test an element not to be in the document.
fireEvent VS userEvent
the majority of the time you should probably use @testing-library/user-event.
fireEvent
- doesn't simulate the real world scenario
- a lightweight wrapper around the browser's low-level `dispatchEvent` API
userEvent
- manipulates the DOM just like a user interaction in the browser would
`fireEvent` dispatches DOM events, whereas user-event simulates full interactions, which may fire multiple events and do additional checks along the way.
References
https://testing-library.com/docs/user-event/intro
'React' 카테고리의 다른 글
React Testing Library test React Router - BrowserRouter vs MemoryRouter (0) | 2024.07.30 |
---|---|
vite stage 개발/배포 모드 cli 설정 (0) | 2024.07.17 |
Mui textfield, select 라벨 여부에 따른 조건부 스타일링 적용 (0) | 2024.06.18 |
Turborepo turbo.json build outputs 빌드결과물 경로 (0) | 2024.05.28 |
react daum postcode service api 우편번호 찾기+위경도 데이터 받아오기 컴포넌트로 분리 (0) | 2024.04.26 |