Explore key concepts and strategies for effective component testing using React Testing Library. This quiz assesses your understanding of best practices, core APIs, and practical techniques for creating robust and reliable tests for React components.
Which query method is most appropriate for selecting a button element by its visible text in a component test?
Explanation: The getByText method is used to select elements by their visible text content, making it ideal for finding a button by its displayed label. querySelector is not a query method provided by the library and focuses on CSS selectors. getByRole can be used to select by role but requires additional options to match text. findAllByLabelText is intended for elements associated with accessibility labels and returns all matching elements, not a single one by text.
If a component shows a message only after a user clicks a checkbox, which step should the test perform to validate this behavior?
Explanation: Firing a click event on the checkbox replicates the user's interaction, allowing the test to validate if the message renders properly. Simulating a server response is unrelated unless the interaction triggers a request. Calling render again would reset the component, hiding state changes. Changing state manually does not represent an actual user interaction and can bypass key logic.
When a component displays data after fetching asynchronously, which query should you use to wait for an element with the text 'Loaded' to appear?
Explanation: findByText is designed for asynchronous queries, allowing the test to wait until the element is present in the DOM. getByText is synchronous and will throw an error if the element is not available immediately. queryAllByRole returns all elements with a certain role but does not wait for their appearance. getByLabelText is used for labeled elements, mainly form controls.
How can you assert that a checkbox rendered by your component has the attribute 'checked' set to true after clicking it?
Explanation: The toBeChecked matcher verifies whether a checkbox or radio button is currently checked, matching the intended assertion. toBeVisible checks for visibility, not checked state. toContainHTML checks for contained HTML, which is less reliable for attribute presence. Directly setting isChecked is not a proper testing method and does not verify the DOM state.
Which approach helps ensure your component is accessible by supporting keyboard navigation in component tests?
Explanation: Simulating tab and key events in tests helps verify that keyboard users can interact with the component, supporting accessibility. Rendering the component in a disabled state prevents interaction and does not check accessibility. Styling elements with colors is related to appearance, not accessibility. Manually editing props does not replicate real user interaction and may miss critical accessibility issues.