QA Automation Labs

Let’s Get Start Playwright For Component Testing

1_410gaT9IiztJa0G16prmUw

Let’s Get Start Playwright For Component Testing

Let’s Get Start Playwright For Component Testing

Early detection of bugs in the software development life cycle (SDLC) can save time and cost.In component testing the approach involves testing individual components or modules in isolation to verify their functionality and ensure they meet requirements. This type of testing can identify issues early in the development process, reducing the cost and complexity of fixing bugs later on.

Playwright can be used for component testing. It provides a way to automate testing of individual components of a web application in a real browser environment.

This blog explained :

  1. How you can Set up the React component
  2. How you can test React component with the help of Playwright

What is component testing?

Component testing is a type of software testing that focuses on testing individual components of a larger system, in isolation from the other components. The goal of component testing is to validate that each component behaves as expected, and meets the specified requirements and functionality, before the components are integrated into the larger system. This approach helps identify and fix issues early in the development process, leading to a more stable and reliable final product.

Playwright for component testing?

Playwright is a popular end-to-end testing framework for web applications that allows you to test web components in a real browser environment. It supports the automation of browsers like Chrome, Firefox, and Safari, and provides APIs for interacting with pages, elements, and debugging.

Playwright supports component testing, which means that you can write tests to specifically target and verify the behavior of individual UI components within your web application. This makes it a useful tool for ensuring the stability and functionality of your application over time as it evolves.

End-to-End testing vs Component testing

End-to-End (E2E) testing and Component testing are two different types of software testing that focus on different aspects of the application.

End-to-end testing:

End-to-End testing involves testing the entire application from start to finish, simulating real-world usage scenarios to verify that the application works as expected from the user’s perspective. The goal of E2E testing is to identify any integration issues between different components of the application and ensure that the application meets the requirements.

Component testing :

Component testing, on the other hand, focuses on testing individual components or units of the application in isolation. The goal of component testing is to verify that each component works as expected and meets the requirements, before integrating it into the larger application.

Below are a few Comparison between End to End Testing Vs Component TESTING

Advantages of component testing

There are various advantages of Component testing few of which are explained below

  1. Improved modularity: Component testing ensures that each component of a system works as expected in isolation, leading to improved modularity and easier maintenance.
  2. Early detection of defects: Component testing enables early detection and correction of defects, reducing the overall cost of fixing bugs.
  3. Improved reliability: By thoroughly testing each component, the overall reliability of the system is increased.
  4. Faster development: Component testing enables developers to test individual parts of a system quickly, leading to faster development and reduced overall development time.
  5. Enhanced collaboration: Component testing allows different teams or developers to work on separate components of a system, enhancing collaboration and reducing the likelihood of conflicts.
  6. Isolation: By testing individual components in isolation, developers can identify and fix issues more easily, rather than having to investigate and debug complex interactions between multiple components.
  7. Faster development: Component testing enables developers to test individual parts of a system quickly, leading to faster development and reduced overall development time.
  8. Faster debugging: Component testing allows developers to quickly identify the source of an issue, rather than having to search through the entire system to find it.
  9. Better test coverage: By testing individual components, developers can ensure that every part of the system is thoroughly tested, which can help to improve overall test coverage.

Pre-request

  1. Node is installed
  2. Vs Code is installed

For Demo purposes, we are using the Counter react component and One another component you will see later in the DEMO.

Set Up React App and Install Playwright

This section describes how to set up React Component, Install Playwright and integrate it with React before you can create component tests.

Step 1

Run the below command in the terminalnpx create-react-app react-app

After running the above command look like the attached below

Step 2

Go into the root directory and run the below command to launch React appcd react-app
npm start

After running the command ‘npm start’ react app with port http://localhost:3000/ is launched.

As you can see in your Visual Studio Code, the project has been created successfully. Let’s see how it looks like attached below

Step 3

You can see that application is started, let’s see how we can get started with the test project for Playwright component testing.

Run the below command to <>npm init playwright@latest — –ct

Once the above command done below option are display to install. Select JavaScript

Once react framework installed successfully you can see the below screenshot

Step 4

Open the VS code and you can see Playwright is installed

Testing React Component Using Playwright

Example 1

Let’s Write First Component Test and Test with Playwright

Lets update name of the existing file src/App.test.js -> App.spec.js and Create App.js file.

Write below code under App.jsimport logo from ‘./logo.svg’;
import ‘./App.css’;

function App() {
return (
<div className=”App”>
<header className=”App-header”>
<img src={logo} className=”App-logo” alt=”logo” />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className=”App-link”
href=”https://reactjs.org”
target=”_blank”
rel=”noopener noreferrer”
>
Learn React
</a>
</header>
</div>

);
}

export default App;

Write the below component test cases under App.spec.jsimport { test, expect } from ‘@playwright/experimental-ct-react’;
import App from ‘./App’;

test.use({ viewport: { width: 500, height: 500 } });

test(‘Verify the text in React Page ‘, async ({ mount }) => {
const component = await mount(<App />);
await expect(component).toContainText(‘Learn React’);
await expect(component).toContainText(‘save to reload’);
});

Lets run the test case using below command npm run test-ct

After running the above command lets run command given belownpx playwright show-report

Output

After running the above command below report display where you can see two text ‘Learn React’ And ‘save to reload’

Example 2

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

Lets give name of js file as ‘QAAutomationLabs.js’ and spec name ‘QAAutomationLabs.spec.js’

Scenario Covered :

  1. Scenario for when we do the increment by clicking on the (+) icon
  2. Scenario for when we do the decrement by clicking on the (-) icon

Create a New Component under src folder

QAAutomationLabs.js file attached belowimport { useState } from ‘react’
export default function Counter({ initial = 0 }) {
const [count, setCount] = useState(initial)

return (
<div style={{
padding: 30
}}>
<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>
)
}

QAAutomationLabs.spec.js attached below

In below test case we are covering two scenario. First ‘Two time Increment in the Counter’. Second scenario ‘Increment then the decrement the Counter’import { test, expect } from ‘@playwright/experimental-ct-react’;
import App from ‘./QAAutomationLabs’;
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’);
});

Lets run the test case using below commandnpm run test-ct

After running the above command lets run command given belownpx playwright show-report

Output

After running the above command below report display

Wrap-up

Component testing along with Playwright is beneficial for several reasons it allows for early detection of bugs, improves code quality, increases confidence in code changes, facilitates refactoring, simplifies integration testing, and is cost-effective.

Additionally, by writing tests for individual components, developers are forced to think about the design and functionality of their code, which can lead to better code quality and maintainability.

Leave a Comment

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

Recent Posts

Let’s Play with Cypress Feature “Test Replay”

Problem Statement Before Cypress v13, test failures in CI have historically been captured through screenshots, videos, and stack trace outputs, b
Read More

Handling Shadow DOM Using Cypress

The idea of componentization has completely changed how we design and maintain user interfaces in the field of web development. The advent of Shadow D
Read More

Gear up for upcoming Conferences of 2024! ✨✨

Gear up for our upcoming Conferences of 2024! ✨ ✨ #TheTestTribe #SoftwareTesting #Testers #Community #Worqference #Worqference2024 #QonfX 
Read More