Questions
This component is failing its test. Fix the component to make the test pass.
A developer wrote a simple Accordion component. It should display a title, and when the user clicks that title, it should reveal the hidden content.
They also wrote a unit test for this component using React Testing Library. The test codifies the exact requirements. However, the test is failing, which means the component has a bug.
This is a test-driven development (TDD) challenge. You are given the buggy component and the failing test.
Your task is to read the test to understand the requirements, then fix the Accordion component so that the test would pass.
import React, { useState } from 'react';
// The buggy component
function Accordion({ title, children }) {
// The state seems to be here, but is it used correctly?
const [isOpen, setIsOpen] = useState(false);
const handleToggle = () => {
// THE BUG: This handler is not implemented correctly.
// It should change the value of `isOpen`.
};
return (
<div>
<button onClick={handleToggle}>{title}</button>
{isOpen && <div>{children}</div>}
</div>
);
}
// This is a wrapper to demonstrate the component visually.
export default function App() {
return (
<Accordion title="Click to Open">
<p>Here is the hidden content.</p>
</Accordion>
);
} import React, { useState } from 'react'; function Accordion({ title, children }) { // The state seems to be here, but is it used correctly? const [isOpen, setIsOpen] = useState(false); const handleToggle = () => { // THE BUG: This handler is not implemented correctly. // It should change the value of `isOpen`. }; return ( <div> <button onClick={handleToggle}>{title}</button> {isOpen && <div>{children}</div>} </div> ); } export default function App() { return ( <Accordion title="Click to Open"> <p>Here is the hidden content.</p> </Accordion> ); }
import React, { useState } from 'react'; function Accordion({ title, children }) { const [isOpen, setIsOpen] = useState(false); const handleToggle = () => { // FIX: Update the state to the opposite of its current value. setIsOpen(!isOpen); }; return ( <div> <button onClick={handleToggle}>{title}</button> {isOpen && <div>{children}</div>} </div> ); } export default function App() { return ( <Accordion title="Click to Open"> <p>Here is the hidden content.</p> </Accordion> ); }
Practice Question
What is the core philosophy of React Testing Library?