📎 Webclip
Introduction to Test-Driven-Development in React for Beginners
The article explains TDD in React through a simple counter. It starts with a test for a Counter component that receives a value prop and then moves to an App that renders the counter with a button that increases the count by one.
Reading notes#
- TDD is presented as writing a test before coding the feature.
- The example uses a simple counter instead of focusing on styling.
- The project is created with
yarn create react-app react-test-driven-developmentand started withyarn start. - A
componentsdirectory is created insidesrc. Counter.test.jsis written beforeCounter.jsx.- The counter test checks that the component renders and shows the value
2. - The test uses
render,screen.getByTestId,toBeInTheDocument, andtoHaveTextContent. - Running
yarn testfails before the component exists, which matches the TDD flow. Counter.jsxrenders a<p>withdata-testid="counter-test"and displaysprops.value.- The next step adds the counter to
App.jswith a button that changes state. App.test.jschecks thatApprenders, the counter starts at0, the button exists, and clicking it changes the counter to1.- The test uses
userEvent.clickto simulate the button press. App.jsusesReact.useState(0)and passes the state value toCounter.- The button calls
setCount(count + 1)when clicked. - The article notes a React 18 warning about
ReactDOM.renderand points to a StackOverflow answer for fixing it. - It ends by saying the next article will cover TDD with Redux and thunk.
