Unit tests for the `Counter` component

Unit tests for the `Counter` component

Setting Up for Testing

First, ensure that your project is set up for testing with React Testing Library and Jest if it’s not already. If you need to set it up, you can refer to the setup instructions from my previous explanation or the official React Testing Library documentation.

Writing Unit Tests

Create a file named Counter.test.js in the same directory as your Counter component. Here, we will write two tests:

  1. Test to check the initial value of the counter.
  2. Test to check if the counter increments correctly when the button is clicked.

Counter.test.js

				
					import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import Counter from './Counter';

describe('Counter Component', () => {
  test('initial counter value is 10', () => {
    render(<Counter />);
    const counterElement = screen.getByTestId('counter');
    expect(counterElement).toHaveTextContent('count : 10');
  });

  test('increments counter value by 1 when increment button is clicked', () => {
    render(<Counter />);
    const incrementButton = screen.getByRole('button', { name: /increment/i });
    fireEvent.click(incrementButton);
    const counterElement = screen.getByTestId('counter');
    expect(counterElement).toHaveTextContent('count : 11');
  });
});

				
			

Explanation

  1. Initial Value Test:

    • The render(<Counter />) function call renders the component into a virtual DOM.
    • screen.getByTestId('counter') fetches the element with the test ID counter, which is expected to be the <h1> tag showing the count.
    • expect(counterElement).toHaveTextContent('count : 10') checks that the text content of this element is indeed “count : 10”, confirming that the initial state is set correctly.
  2. Increment Functionality Test:

    • After rendering the component, it fetches the button responsible for incrementing the counter using screen.getByRole('button', { name: /increment/i }).
    • fireEvent.click(incrementButton) simulates a user clicking the increment button.
    • It then re-checks the <h1> element to see if the count has been incremented correctly to “count : 11”.

Running the Tests

To run your tests, execute the following command in your terminal:

				
					npm test

				
			

This command will invoke Jest to run the test suite, which includes the two tests we’ve written for the Counter component. Watch the output in your terminal to see if both tests pass successfully, which would confirm that your component initializes and behaves as expected under test conditions.

             These tests ensure that your `Counter` component not only starts with the correct initial value but also responds correctly to user interactions. 

Overview

Leave a Reply

Your email address will not be published. Required fields are marked *

Enquire Now