getBy throws khi không có (test fails fast); queryBy returns null (dùng để assert absent); findBy async (dùng cho sau API call) — ưu tiên getByRole > getByLabelText > getByTestId.
- Ba nhóm queries trong @testing-library/react với behavior khác nhau khi element không tồn tại: getBy: throw error ngay lập tức nếu không tìm thấy — dùng khi element phải có (fail fast, rõ ràng nhất). queryBy: trả về null nếu không tìm thấy — dùng khi muốn assert element không có:
expect(queryByRole('alert')).not.toBeInTheDocument(). findBy: trả về Promise, wait cho element xuất hiện (mặc định 1000ms, configurable) — dùng cho async operations như API calls. - Tương tự cho multiple elements: getAllBy/queryAllBy/findAllBy.
- Priority order (Testing Library khuyên dùng theo thứ tự ưu tiên): getByRole > getByLabelText > getByPlaceholderText > getByText > getByDisplayValue > getByAltText > getByTitle > getByTestId.
- Role-based queries
getByRole('button', { name: 'Submit' })là tốt nhất vì test user-visible behavior và verify accessibility. - Không dùng
getByTestIdcho mọi thứ —data-testidlà last resort, liên kết test với implementation details. waitFor pattern:await waitFor(() => expect(screen.getByText('Loaded')).toBeInTheDocument())— retry assertion cho đến khi pass hoặc timeout.