Testing React Components — Concept Check
Questions on Testing React Components. Testing Library's whole philosophy is to interact with a component the way a user does. Query by role and text, not by class name or component internals.
Questions in this quiz
8 questions on Testing React Components — Concept Check. Work through them here, then start the quiz to answer them and see your score.
1.You have a React component that should display a loading spinner while fetching data. Which test approach aligns with Testing Library's philosophy?
- ATest that the component's internal loading flag is true.
- BVerify the component's state is set to loading during data fetch.
- CCheck the presence of a spinner element using getByRole when fetching starts.
- DEnsure the component contains a div with class 'spinner' when fetching.
2.A developer writes a test for a button click using fireEvent. What is a better alternative according to Testing Library?
- AUse querySelector to find the button and trigger a click event.
- BUse userEvent to simulate a real user's interaction.
- CCheck the button's role attribute to ensure it's a button.
- DDirectly call the button's onClick handler.
3.You notice a test fails because getByRole cannot find a button. What should you check first?
- ACheck if the component's state updates correctly.
- BMake sure the button is wrapped in a div.
- CEnsure the button has an accessible role and name.
- DVerify the button's class name is correct.
4.When testing a form input, which query method should you prefer to ensure accessibility?
- AgetById
- BgetByClassName
- CgetByLabelText
- DgetByPlaceholderText
5.A test using await findByRole fails intermittently. What is a likely cause?
- AThe component's CSS is not loaded correctly.
- BThe test uses an incorrect role for querying.
- CThe test lacks proper waiting for asynchronous operations.
- DThe component's state is not being set properly.
6.Which of the following is NOT recommended when writing tests for React components?
- ATesting conditional rendering based on user actions.
- BTesting for the presence of elements using getByRole.
- CSimulating user interactions with userEvent.
- DAsserting component state directly for expected values.
7.A developer uses getByTestId to find elements in tests. What is a potential downside of this approach?
- AIt bypasses accessibility checks that other queries provide.
- BIt is the most reliable method for finding elements.
- CIt ensures the test is tightly coupled with component internals.
- DIt is the fastest way to locate elements in the DOM.
8.Which query method would you use to assert that an error message is NOT present in the document?
- AgetByText
- BfindByText
- CqueryByText
- DgetByRole