DEV Community

Sagarkumarnri
Sagarkumarnri

Posted on

TDD with React

What is TDD?
TDD stands for Test-Driven Development." This is an approach to developing your code after writing its test cases. Here, the test cases will drive the development of your code. In simple terms, first you write the test cases for what you are going to develop, and then you start the actual development.
Developing a React application with the TDD approach
Let’s suppose you want to create a user sign-in component. Before creating the component, let's identify the elements that are required to build the whole component. Let’s see the step-wise approach that we need to follow for TDD.
Step 1:
Create an empty component

const Signin= () =>{}; export default Signin;
Enter fullscreen mode Exit fullscreen mode

Step 2:
Assume that you have a header element, and write a test case to verify that the header element is present in your component when it renders. If you don’t have any, the test case should fail.
Write a test case using the React testing library.

import "render, screen" from "@testing-library/react";
import Signin from ". /pages/signin"
test ("Signin header should be present"), () =>
render(<Signin/>)
const header=screen. getByText(/Signin/i);
expect(header).   toBeInTheDocument ();
})
Enter fullscreen mode Exit fullscreen mode

Now run the command "npm test." If your test fails, then you are going in the right direction because you haven’t added the element to your component yet.
Step3:
Now add the element to your component.

const Signin = () =>

 <h3>Signin</h3>
export default Signin;
Enter fullscreen mode Exit fullscreen mode

Run your test again and expect it to pass. If your test case passes, then you have the approach; now repeat these three steps for every other element that you want to add to your component.

Top comments (0)