# Test your react component using Playwright

Testing is an integral part of the software development process. When it comes to web development, testing React components is crucial to ensure that your application functions as expected. Playwright is a powerful tool that can help you automate browser interactions and effectively test your React components. In this article, we'll explore React component testing using Playwright, providing you with a comprehensive guide to get started.

## **What is a Playwright?**

Playwright is an open-source automation framework that enables developers to test web applications across different browsers, including Chromium, Firefox, and WebKit. Developed by Microsoft, Playwright offers a unified API for automating browser actions, making it an excellent choice for end-to-end testing and browser automation.

## **Why Use Playwright for React Component Testing?**

Playwright is an excellent choice for React component testing for several reasons:

1. **Cross-Browser Testing**: Playwright allows you to test your React components in multiple browsers, including Chromium, Firefox, and WebKit. This ensures that your components work consistently across different browsers, which is crucial for delivering a great user experience.
    
2. **Real User Interactions**: Playwright can simulate real user interactions, such as clicking, typing, and navigating. This helps you test your React components in a way that closely resembles how users interact with your application.
    
3. **Headless and Headful Mode**: Playwright supports both headless and headful modes, making it versatile for different testing scenarios. You can run tests headlessly for continuous integration (CI) pipelines or run them in headful mode to visually inspect the test execution.
    
4. **Accessibility Testing**: Playwright includes built-in accessibility testing tools, allowing you to ensure that your React components are accessible to all users, including those with disabilities.
    

## **Set Up React App**

Step 1 - Create a react app using the given command.

```bash
npx create-react-app react-app
```

After running the above command output looks like

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1695578205500/4d5fce16-e0e0-41b0-a3dd-9baa8414f2ce.png align="center")

Step 2 - Go to the root directory and launch the React app.

```bash
cd react-app
npm start
```

After running the npm start command your react app will be started on *http://localhost:3000*

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1695578872389/26be8712-b0a3-48f6-a3c1-f30197b29799.png align="center")

Take a look at your Visual Studio Code - the project has been successfully created. Now, let's see what it looks like, shown below.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1695578992544/17cef274-12a9-4f9d-b311-36ff3d0fd7b2.png align="center")

Notice that the application is up and running.

## Set up Playwright

Step 1 - Run the below command to initiate Playwright in react-app that you have created.

```bash
npm init playwright@latest -- --ct
```

After running the given command output will look like

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1695580271420/37838f4f-d437-49bb-a491-403c62fc4bb6.png align="center")

Select**Javascript** by pressing the down arrow button + enter.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1695580414003/7af63a4f-8222-4953-b47e-a50a26891f56.png align="left")

Select **React 18**

Now, Playwright is initiated in your project you can see screenshoot.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1695580594548/1f9690d4-b939-478a-b3be-dfe30d05162a.png align="center")

Now you can see, that Playwright is installed in your project.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1695580790159/a555e63b-b43d-4de0-8ab4-f973deb6f3cd.png align="left")

## Test your react component.

Now Let’s take an example to test **Counter** Component using Playwright.

**Step 1** - update the name of the existing file **src/App.test.js -&gt; App.spec.js**

**Step 2** - Create a Counter component.

Let's give the name of the js file as ‘Counter.js’ and the spec name ‘Counter.spec.js’

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1695581923348/c5d4666e-6f01-438f-9565-3465e9b47534.png align="left")

**Step 3** - Paste the following code to `Counter.js` file

```javascript
import { useState } from 'react'
export default function Counter({ initial = 0 }) {
    const [count, setCount] = useState(initial)

    return (
        <div>
            <button style={{ color: "black", backgroundColor: "green", margin: 10 }} aria-label="decrement" onClick={() => setCount(count - 1)}>
                -
            </button>
            <span data-cy="counter">{count}</span>
            <button style={{ color: "black", backgroundColor: "green", margin: 10 }} aria-label="increment" onClick={() => setCount(count + 1)}>
                +
            </button>
        </div>
    )
}
```

**Step 4** - Paste the following code to `Counter.spec.js` file.

```javascript
import { test, expect } from '@playwright/experimental-ct-react';
import App from './Counter.jsx';
const counterSelector = '[data-cy="counter"]';
const incrementSelector = "[aria-label=increment]";
const decrementSelector = "[aria-label=decrement]";
test.use({ viewport: { width: 500, height: 500 } });

test('Two time Increment in the Counter ', async ({ mount }) => {
    const component = await mount(<App/>);
  await component.locator(incrementSelector).click();
    await expect(component.locator(counterSelector)).toHaveText('1');
    await component.locator(incrementSelector).click();
    await expect(component.locator(counterSelector)).toHaveText('2');
});

test('Increment then the decrement the Counter ', async ({ mount }) => {
    const component = await mount(<App/>);
  await component.locator(incrementSelector).click();
    await expect(component.locator(counterSelector)).toHaveText('1');
    await component.locator(decrementSelector).click();
    await expect(component.locator(counterSelector)).toHaveText('0');
});
```

In the above test case, we are covering two scenarios. First ‘Two time Increment in the Counter’. The second scenario is ‘Increment then the decrement the Counter’.

**Step 5** - Run the test cases using the below command.

```bash
npm run test-ct
```

**Step 6 -** See output using the below command.

```bash
npx playwright show-report
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1695582680221/437770bb-ebce-4a96-b389-6c327afe3d5d.png align="left")

Now you can see the test report of the Counter component.

Find Source Code Here: [https://github.com/theatulanand/react-playwright](https://github.com/theatulanand/react-playwright)

Follow us for more articles related to software development and testing.
