How To Get Started With Playwright Component Testing

  • Learning Hub
  • How To Get Started With Playwright Component Testing

OVERVIEW

Playwright provides multiple fascinating features to work with and to help improve your tests, and how it works can speed up your tests massively. Playwright is one of the pioneers of it. This is not available in Selenium, but it can be tried with Cypress (available as a beta version).

playwright component testing
Source

The latest release of Playwright (v1.27) comes with exciting new features, especially for those working with front-end projects.

As you are reading this, you might be already thinking about what we are talking about, right? If not, here’s a clue.

“It is an independent and reusable bit of code. They come into two types, classes and functions”.

Did you get it by chance? Yes? Alright, we are talking about Components.

When it comes to front-end development, libraries like React are very popular. For those who have never worked or even heard about it, it allows developers to create user interfaces quickly and easily. It was created by Facebook and is now maintained by a huge community.

But of course, after creating an application, we must ensure it works properly. Hence, we need to test it!

Before going deeper into this particular Playwright feature, let’s understand why Playwright component testing is essential and how it can help you to improve testing.

What is Component Testing

Component testing is a type of testing where these objects (components) can be tested in isolation, independently, without integrating them with other parts of the application.

So, for those familiar with it, Jest offers an excellent way of testing your components. It renders the components in a virtual environment (JSDom, for example) and lets you run some tests against them so that you can test your components in Isolation.

So, for those familiar with it, Jest offers an excellent way of testing your components. It renders the components in a virtual environment (JSDom, for example) and lets you run some tests against them so that you can test your components in Isolation.

That is pretty cool, right? But what if you are able to mount those components in a real browser and interact with them as you do with any end to end test?

But you might be asking why I need that.

Well, that is a very valid question, but there is also a good reason. Let’s check it.

Component Testing vs Unit Testing

As stated in the above section of this tutorial on Playwright component testing, rendering the components in a virtual JS environment is sometimes not enough; it is purely JS and does not even act as a real browser.

This is one of the main differences between Unit testing and Component testing.

When you need to test some complicated ones like a scroll bar or a slider, JSDom is not enough. There is probably a way of mocking everything, but it is also quite complicated and takes time. Of course, you can mix both and increase your coverage and the quality of your product; it does not need to be one or the other.

In this tutorial on Playwright component testing, you will learn to set up your first front-end application using React and start testing those components. Let’s have a look!

Behind the scenes

Playwright used Vite as a build tool. When the tests are executed behind the scenes, Playwright creates a bundle with the components needed for the test and serves them using a static server. The components get generated in the index.html by using the mount command.

Mounting means the component will be added to the DOM. When the component is just created, it is nothing else than plain JavaScript, a virtual representation of the component.

Mounting turns that virtual into a real and final representation of that component in the DOM.

Creating a React application for Playwright component testing

React is an Open-Source library that facilitates developers to write user interfaces quickly. It is very popular and was created by Facebook around 2011. It has a huge community maintaining it nowadays and millions of downloads.

react application for playwright component testing

Its current version is v18, and according to the GitHub repository, React is used by 11.4 million users!

github repository

Installing React

Time to practice, let’s take our first step and install React for this Playwright component testing tutorial:

  • Open Visual Studio Code.
  • Open a new terminal.
  • Run the following command on the terminal.
npx create-react-app myAppName
installing-react-min

Name

Done!

playwright component testing npm start

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

component app

Project Structure

But what are all these folders and files?

We went through node_modules, package-lock.json, .gitignore, and package.json in the previous tutorial on Playwright end to end testing when learning how to set up Playwright.

Public Folder:

  • favicon.ico: This is a small image linked to a page or app. In our case, it is the react image and will be displayed in the Tab with the page title.
  • index.html: Main HTML entry. This provides a structure or content for your application to render.
  • logos: Src Folder: React logos, png files.
  • manifest.json: This is where you will find some information about your app. It could be the author, resources, versions, etc.
  • robots.txt: It decides whether crawlers are allowed or not. Crawlers are programs to navigate and collect data from apps.

Src Folder:

  • App.css: Contains styles for our application components.
  • App.js: This function returns the code for our application component. This is the main component of the app.
  • index.css: Styles for index.js.
  • index.js: This file contains the function that tells your App Component to be rendered in a particular element of the index.html, called “root”.
  • logo.svg: Vector graphics image.
  • reportWebVitals.js: This file helps us to measure the performance of our app.
  • setupTest.js: This file only imports the library for JSDom and gives us access to it.

Now that we know what has been created, let’s try to run it and see how our app looks. But how? Can we do that already? Is it not too soon? Well, as mentioned in the above section of this tutorial on Playwright component testing, React lets you create a simple app easily :)

Starting the App

If we look at the package.json file, we will see a “scripts” section. There is a command called “start”. Let’s move to our app in the terminal and execute that command.


cd component-app
npm start
npm start page

Nice! The React App is already up and running!

Installing Playwright Components Module

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

The Playwright Components is an Experimental feature, which is why the module is called experimental-ct. So, in your terminal, you can run the following command:


npm init playwright@latest - -  - -ct

You will be prompted with some questions about the language (we are going to use TypeScript) and which framework you want to use (we are using React).

Shown below is the terminal output:

terminal output

Once installed, you should see the below output:

playwright test project

Playwright Component Structure

When the Playwright Component module gets installed, it automatically generates some folders and files for you, so you might notice that your project structure changed a little bit. Let’s inspect what is in it now:

,
playwright component structure
  • playwright: A new folder has been created; it contains two files.
  • index.html: This file will be used by Playwright to mount your component, and it will do it in the same way as React > Public > index.html by using the “root” element.
  • index.ts: This file is for you to include themes, styles, or even apply code for the page where your component will be mounted.
  • playwright-ct.config.ts: The playwright configuration file where you can set up your browser, timeouts, etc.

Now you have both your application running and your test framework installed. Time to give them a try!

Creating the Test File

You might be experienced in how to create a test file for Playwright component testing already, but it is always good to have a quick reminder. So, let’s use the existing “src” folder and create “tests” under it, and of course, our test file, called: components.spec.tsx.

Now the extension of our file is .tsx instead of .ts, why ?. React components use JSX syntax, so for our files to accept/embed/support that, we need to update the extension from .ts to .tsx.

test file

Writing the Test

Alright, we are almost there. Now we need to add some code to our new test class. Here is what a simple component test looks like:

writing the test

Allowing JSX

React components are typically written in JavaScript. JSX is a JavaScript extension that stands for JavaScript XML. It provides a way to structure the components more easily by allowing us to write HTML in React.

Before sharing this code with you, I want to give you a heads-up. As you can see in the image, something seems wrong with that <App> . This is because we need to enable JSX.

To do that, we can go to our tsconfig.json and add this line into the compiler options:


“react-jsx”

And save it.

The tsconfig.json will look like this:


{
    "compilerOptions": {
        "jsx": "react-jsx",
        "target": "ESNext",
        "module": "commonjs",
        "moduleResolution": "Node",
        "sourceMap": true,
        "outDir": "../tests-out",
    }
 }

Solved!

Now, let’s slightly update our App.js component by changing the text. Open the file, and replace “Learn React” with “My First Component”.


import { test, expect } from '@playwright/experimental-ct-react';
import Header from '../../src/header';
import App from '../../src/App';


test('App should work', async ({ mount }) => {
  const component = await mount(<App></App>);
  await expect(component).toContainText('My First Component');
});

Understanding the Test

Here we have a very simple test for Playwright component testing. As with any other Playwright test , we first need to import our modules, in this case, the experimental-ct-react we installed at the beginning.

We are also importing our App.js component. This is for the test to be able to mount it.

Then we have the test itself. What do we have here? Instead of using “page” or “request” as fixtures in the test, we are using something called “mount”, but what is that? Alright, “mount” basically allows us to put the component into the DOM to render it.

That is why, if you check the test, you will notice that we are passing our App into the mount method, which will be responsible for rendering our component in the browser.

The final step is just an assertion.

But why is this so powerful? Well, as explained before, this is a combination of the power of Node.js to render your components without spinning up the whole application and use all the features that Playwright provides!

And even more important, this will be created and tested in a REAL browser.

Now the proof of truth, we need to run the test!

When installing our Playwright Components module, it does something else for us. If we go and check the package.json file, we will see something new.

 understanding the test

Yes, Playwright has added a new command for us to execute our test, so let’s try that.

Running the Test

I am going to run it from the terminal, but you can also do it using the extension.

Let’s run: npm run test-ct

running the testplaywright component testing 001

Have you seen that? The screen can barely be seen as the test runs blazing fast! It is almost impossible to see the application being rendered, right?

Debugging the Test

But let's do something for you. We will debug the test, so you will know it is happening!

debugging the test minfirst component

And done! The test passed!

Adding more Components to App

Now, let’s try and create a new, fresh and simple component. Under the “src” folder, we are going to create a file called “header.js”

Open the file and paste this code, which is very similar to what we have on our App.js, but simpler:


function Header () {
  return (
    <header>
       <h1>Header Testing Component</h1>
    </header>
  )
}
export default Header

Okay. The header component is already created.

Now, what we are going to do, is to include that header as part of our App.js, so open that file and follow these steps:


import Header from './header'

Now, below the first <div> in the App insert your header node, like this:


function App() {
  return (
    <div className="App">
       <Header/>
      <header className="App-header">

Well.. that’s all :) your header now should be rendered as part of your App. Let’s give it one more try. You can debug the test or run the “npm start” command and check your application is running.

run the npm start

Can you spot the difference now, right? Check the top of your app, the header is displayed there.

If we add one more assertion to our test, we should be able to make sure that our new component is displayed and has the correct text; let’s try.

Updating the Component

Your component can be customized as you prefer. It is a good practice to add your unique attribute value to identify your elements easily.

For example, we can add an attribute called “qa-id” to the header component, and once it is rendered, we will be able to find it by that unique value. Let’s see how it works:

Open your header.js and update the code with this:


    <header>
       <h1 qa-id="header-component">Header Testing Component</h1>
    </header>

Done, now that you have updated your component and added the attribute, we will update the test and try to find it.

Updating the Test

We will use the page fixture now, as I would like to find my new locator and ensure it has the correct text displayed.


test('should work', async ({ mount, page }) => {
  const component = await mount(<App></App>);
  await expect(component).toContainText('Learn React');
  await expect(page.locator("[qa-id='Header']")).toHaveText("Header Testing Component")
  page.close()
});

Cool, do you think it will pass? Let's have a look.

Updating the Test

Yes it did! Let’s update the text of the assertion to see if we can make it fail. We will make it lowercase instead.


await expect(page.locator("[qa-id='Header']")).toHaveText("header testing component")
                                

And … moment of truth..

update the assertion

As we can see, the test just failed.

Testing Header Component in Isolation

Alright, now the final part is to make sure we can test this new component completely independently, without the need for our App and just as it is.

How do we do that?

Let’s go to our component.spec.tsx and change the import. Instead of App, you will need to import your header, something like this:


import Header from '../../src/header';
                            

And now, in the test itself, replace your App component for Header.


import { test, expect } from '@playwright/experimental-ct-react';
import Header from '../../src/header';
test.use({ viewport: { width: 500, height: 500 } });

test('should work', async ({ mount, page }) => {
  const component = await mount(<Header></Header>);
  await expect(page.locator("[qa-id='Header']")).toHaveText("Header Testing Component")
  page.close()
});

Time to debug the test and see what is there.

debug the test

Great!

So now your new component is rendered without needing to spin up the whole app, and you can test it in isolation.

Visual Testing of Components

We can even take screenshots of our components to do some visual testing!


await expect(page.locator("header>h1")).toHaveScreenshot()

First try:

First try

Retry:

retry

As you can see, the screenshot has been generated, and now, every time you execute this test, it will compare the new image with the existing one in your project.

Launching the App on the Cloud Grid

You can also launch your application and start a Real Time browser testing by configuring a tunnel in LambdaTest. When it comes to Playwright browser testing, LambdaTest is designed to help you perform cross browser testing. It provides an online browser farm of 50+ browsers and browser versions of Chrome, Chromium, Microsoft Edge, Mozilla Firefox, Opera, and even Webkit for Playwright component testing.

Subscribe to the LambdaTest YouTube Channel and stay updated with the latest tutorial around automated browser testing, Cypress E2E testing, mobile app testing, and more.

The tunnel will create a secure connection between your computer and LambdaTest. Once the tunnel is configured, you can press START and test your app.

tunnel is configured

Enhancing Playwright Component to Existing Project

If you already have a React and have already set up Playwright, or if by chance (this was my personal experience) you are working behind a proxy, your npm register could be cached. You cannot init Playwright experimental. There is another way to do it.

As experimental-ct is a module, it can be installed as any other npm module just by running a command on the terminal.

“npm install @playwright/experimental-ct-react”

This will include the module as part of your project under node_modules. And you will also be able to see it installed on your package.json.

installed on package.json

But as we have installed the module manually, a few folders and files need to be added to your project. These are the ones that were created automatically when we installed Playwright before. Don’t worry; it can be achieved with a few clicks, which is not that much, so let’s look at that:

Adding Missing Files

First, create the Playwright folder. You will need to create two files in this folder:

  • index.html
  • index.ts

Once you have created that, you can copy and paste the code from their official documentation into your index.html as stated there.


<html lang="en">
 <body>
   <div id="root"></div>
   <script type="module" src="/playwright/index.ts"></script>
 </body>
</html>

Done.

Adding Script

Keep in mind the script in the package.json file will also need to be added for you to execute the tests.


"test-ct": "playwright test -c playwright-ct.config.ts"
                                

Now you are ready to keep moving with it!

Are you passionate about automation testing? Are you looking to deepen your expertise in Playwright or modern web application testing? Look no further, as this Playwright 101 certification is the perfect measure of your expertise as a Playwright automation tester.

Conclusion

Alright, so as we've seen, you can now render your component instead of the whole application; let that sink in.

  • No need to wait for all the resources to be loaded (images, scripts, fonts).
  • No need to wait for any other component to be done (i.e., if the feature is still in progress).
  • It executes fast.
  • Easier to test.

This feature can help improve your test to easily write very small (atomic) scenarios and test them in isolation in a real browser.

I hope you enjoy this tutorial on Playwright component testing and can get some knowledge from it! Let's keep testing!.

Frequently Asked Questions (FAQs)

Can Playwright be used for unit testing?

Yes. Playwright is a tool that allows a team to write, run and maintain automated tests. This can be done in several ways, along with the variety of tools available for unit testing.

Can we use Playwright for performance testing?

Playwright is a handy tool for testing out some of the most basic functionality of your app—it can help you find any obvious issues with it and ensure that your pages load quickly and don't have any HTML errors.

Was this article helpful?

Helpful

NotHelpful