Show List

Building a unit test

Let's create a simple React component and write a unit test to test its functionality.

Step 1: Create a React Component

Let's create a simple Counter component that increments a count when a button is clicked.

Create a file named Counter.js inside the src directory with the following content:


import React, { useState } from 'react'; const Counter = () => { const [count, setCount] = useState(0); const incrementCount = () => { setCount(count + 1); }; return ( <div> <p>Count: {count}</p> <button onClick={incrementCount}>Increment</button> </div> ); }; export default Counter;

Step 2: Write a Unit Test

Create a file named Counter.test.js inside the src directory with the following content:


import React from 'react'; import { render, fireEvent } from '@testing-library/react'; import Counter from './Counter'; test('increments count when button is clicked', () => { const { getByText } = render(<Counter />); const incrementButton = getByText('Increment'); const countText = getByText('Count: 0'); // Verify initial count is 0 expect(countText).toBeInTheDocument(); // Click the button fireEvent.click(incrementButton); // Verify count is incremented to 1 expect(getByText('Count: 1')).toBeInTheDocument(); // Click the button again fireEvent.click(incrementButton); // Verify count is incremented to 2 expect(getByText('Count: 2')).toBeInTheDocument(); });

Step 3: Run Tests

Run the tests using the following command:


npm test

Step 4: Review Test Results

Jest will run the tests, and you should see output indicating whether the tests passed or failed.

Step 5: Explore Further

You can further explore writing unit tests for React components by testing different scenarios, including edge cases, error handling, and component interactions.

By following these steps, you've created a simple React component and written a unit test to test its functionality using Jest and React Testing Library. You can now continue building your components and writing tests to ensure their correctness.


    Leave a Comment


  • captcha text