DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • Building a Tic-Tac-Toe Game Using React
  • Angular vs. React: Which To Choose for Front-End in 2024
  • Next.js vs. React: The Ultimate Guide To Choosing the Right Framework

Trending

  • Building an AI/ML Data Lake With Apache Iceberg
  • Simplifying Multi-LLM Integration With KubeMQ
  • The Perfection Trap: Rethinking Parkinson's Law for Modern Engineering Teams
  • Understanding the Shift: Why Companies Are Migrating From MongoDB to Aerospike Database?
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Start Playwright for Component Testing

Start Playwright for Component Testing

This approach helps identify and fix issues early in the development process, leading to a more stable and reliable final product.

By 
Kailash Pathak user avatar
Kailash Pathak
DZone Core CORE ·
Apr. 17, 23 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
5.1K Views

Join the DZone community and get the full member experience.

Join For Free

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 the testing of individual components of a web application in a real browser environment.

This blog explained:

  • How you can Set up the React component.
  • 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 comparisons 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

  • Improved modularity: Component testing ensures that each component of a system works as expected in isolation, leading to improved modularity and easier maintenance.
  • Early detection of defects: Component testing enables early detection and correction of defects, reducing the overall cost of fixing bugs.
  • Improved reliability: By thoroughly testing each component, the overall reliability of the system is increased.
  • Faster development: Component testing enables developers to test individual parts of a system quickly, leading to faster development and reduced overall development time.
  • 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.
  • 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.
  • Faster development: Component testing enables developers to test individual parts of a system quickly, leading to faster development and reduced overall development time.
  • 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.
  • 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 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 terminal.

JavaScript
 
npx create-react-app react-app


After running the above command, look like the attached below.

command result

Step 2

Go into the root directory and run the below command to launch React app.

JavaScript
 
cd react-app
npm start


After running the command, the ‘npm start’ react app with the port is launched.

After running the command, the ‘npm start’ react app with the port is launched.

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

 Visual Studio Code


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 <>.

JavaScript
 
npm init playwright@latest -- --ct


Once the above command is done below options are displayed to install. Select JavaScript.

JavaScript successful


React successful

Once React framework is installed successfully, you can see the below screenshot.

React framework is installed successfully


Step 4

Open the VS code, and you can see Playwright is installed.

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

Let's update the name of the existing file src/App.test.js -> App.spec.js and Create an App.js file.

src/App.test.js -> App.spec.js

Write the below code under App.js.

JavaScript
 
import 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.js.

JavaScript
 
import { 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');
});


Let's run the test case using the below command.

JavaScript
 
 npm run test-ct


After running the above command, let's run the command given below.

JavaScript
 
npx playwright show-report


Output

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

Learn React

Verify the text in React Page


Example 2

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

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

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 the src folder.

The QAAutomationLabs.js file is attached below.

JavaScript
 
import { 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 is attached below.

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

JavaScript
 
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');
});


Let's run the test case using the below command.

JavaScript
 
npm run test-ct


After running the above command, let's run the command given below.

JavaScript
 
npx playwright show-report


Output

After running the above command, the below report displays.

QAAutomationLabs.spec.js

Two time increment in the counter.


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.

JavaScript Software testing Virtual screening Visual Studio Code React (JavaScript library) Testing

Published at DZone with permission of Kailash Pathak. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • Building a Tic-Tac-Toe Game Using React
  • Angular vs. React: Which To Choose for Front-End in 2024
  • Next.js vs. React: The Ultimate Guide To Choosing the Right Framework

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!