Testing is Crucial for Software Quality
Testing is crucial for ensuring a software product works as expected. Traditionally, QA teams often manually execute a lot of end-to-end tests for web applications. However, QA teams spend a considerable amount of effort preparing testing data, implementing the tests, and maintaining them over time. The tests are also flaky since they require integration between multiple services, third-party dependencies, and databases. These issues are why component testing for web applications is important and is now getting more attention from both software developers and QA engineers. Component testing allows them to test their graphical user interface (GUI) early, and it reduces the time and effort they need to implement, create, execute, and maintain the tests over time.
Playwright: A Tool for Component Testing
Playwright, a convenient tool for end-to-end testing and interacting with web browsers in general, recently started supporting component testing. It allows developers to write tests for their GUI without waiting for backend services to be completed and without creating a bunch of mock APIs in the mock servers to integrate with. In addition, Playwright has features that support component testing with some popular web frameworks like React, an open-source JavaScript library for building user interfaces. It also has support for major browsers such as Chromium, Firefox, and WebKit-based browsers. You can also use multiple client languages, such as Java, Python, C#, or Node.js, to write tests in Playwright.
In This Tutorial
In this tutorial, you will implement Playwright for component testing with an existing React application. You will deploy a weather app using React and then use Playwright to write and run component tests for the app to ensure the components are working properly.
Prerequisites
To follow along with this tutorial, you will need the following:
- An Ubuntu 20.04 server with a sudo-enabled, non-root user and at least 2GB of RAM. To get started, follow our Initial Server Setup Guide for Ubuntu 20.04.
- Node.js version 16 or greater set up on your server. To install Node.js, follow Option 2 of our tutorial How To Install Node.js on Ubuntu 20.04 to ensure you are installing the correct version.
- Git installed on the server. Read our tutorial How To Install Git on Ubuntu 20.04 to install Git if it is not already installed.
- Familiarity with front-end development using JavaScript with React.
- Knowledge of end-to-end testing, unit testing, and API testing.
Step 1 — Deploying a Weather App Using React
In this step, you will deploy the React-based weather app you will need for this tutorial. The app uses the free version of OpenWeather’s APIs to access current weather data in any city.
To deploy the app on your server, first create a new directory to store the code for the application and then change to the newly created directory. Make sure to replace Projects with your preferred directory name:
mkdir Projects cd Projects
Next, clone the application code from GitHub:
git clone https://github.com/do-community/react-component-testing-demo.git
Step 2 — Installing the Test Dependencies
In this step, you will install the test dependencies so that you can implement component testing with Playwright later in Step 3.
To begin, run the following command:
npm init playwright@latest -- --ct
This command initiates the code generation process that will allow you to write tests using Playwright. Based on your selected choice, whether you are using TypeScript or JavaScript, or using the React framework or Vue framework for development, the auto-generated code will be different.
You will get the following output in your console:
Need to install the following packages: create-playwright@1.17.123 Ok to proceed? (y)
Press Y and then Enter to proceed. You will then be given the option to choose whether you want to use TypeScript or JavaScript in your project:
Getting started with writing end-to-end tests with Playwright: Initializing project in '.' ? Do you want to use TypeScript or JavaScript? … TypeScript ▸ JavaScript
Choose JavaScript since you will be using that for component testing later in Step 3. The output will then ask which framework you want to use:
? Which framework do you use? (experimental) … ▸ react vue svelte
Choose react since that is what the weather application uses. The output will ask whether you want to install Playwright browsers:
? Install Playwright browsers (can be done manually via 'npx playwright install')? (Y/n) ‣ true
Choose Y to install them so that you do not have to install them manually later.
Next, you will be asked whether you want to install the operating system dependencies:
Install Playwright operating system dependencies (requires sudo / root - can be done manually via 'sudo npx playwright install-deps')? (y/N) ‣ yes
Choose Y so that you do not have to install the dependencies manually. Note that you need to input the user password for the machine you’re currently running in order to install the system dependencies.
All the necessary dependencies will now be installed, as well as three browsers: Chromium, Firefox, and WebKit. In addition, a new directory named
playwright
is created, which consists of theindex.html
andindex.js
files needed to render the components during testing. Also, a new configuration file namedplaywright-ct.config.js
is generated for running component testing. You can customize this configuration file in order to change the behavior of the component test, such as whether you want it to run only in the Chromium browser.Note: The script
test-ct
should be automatically generated in thepackage.json
file as displayed below:"scripts": { "start": "react-scripts start", "test-ct": "playwright test -c playwright-ct.config.js" },
You are now done setting up the dependencies for component testing. In the next step, you will write the test for one of the two weather app components.
Step 3 — Writing the Component Test for CityComponent
The weather app has two components: CityComponent and WeatherInfoComponent. In this step, you will write the script for the component test for the CityComponent. In this code, you will be writing two tests for the CityComponent. The first test will check whether the city input box accepts text input. The second test will check whether the Search button executes the fetchWeather method after the button is clicked.
To begin, navigate to the
src
directory:cd src
Then, create the
tests
directory to store your test:mkdir tests
Next, navigate to the newly created directory:
cd tests
Now, in the
tests
directory, create and open a new test file namedCityComponent.spec.jsx
using nano or your preferred code editor:nano CityComponent.spec.jsx
Add the following code to your file:
import { test, expect } from '@playwright/experimental-ct-react'; import { CityComponent } from '../modules/CityComponent'; const cityLocator = '[placeholder="City"]'; const searchButtonLocator = '[type="submit"]'; const cityName = 'Hanoi'; test('cityField accepts text input', async ({ mount }) => { const cityComponent = await mount(); const cityField = cityComponent.locator(cityLocator); await cityField.fill(cityName); await expect(cityField).toHaveValue(cityName); }); test('Click on `Search` button executes fetchWeather prop', async ({ mount }) => { let isCalled = false; const cityComponent = await mount( isCalled = true} /> ); await cityComponent.locator(cityLocator).fill(cityName); await cityComponent.locator(searchButtonLocator).click(); expect(isCalled).toBeTruthy(); });
Save and close your file. If using nano, save and exit by pressing
CTRL+X
.You have now written the script for the component test for the CityComponent, which contains two test blocks—one to check whether the city input box accepts Hanoi as input and one to test whether the Search button executes the fetchWeather method after the button is clicked. In the next step, you will write the component test for the second weather app component, WeatherInfoComponent.
Step 4 — Writing the Component Test for WeatherInfoComponent
In this step, you will write the test for WeatherInfoComponent, the second component of the weather app that you are testing. The test checks whether the weatherComponent contains the text Hanoi after receiving Hanoi as the weatherInfo input.
First, in the
tests
directory, create and open a new test file namedWeatherInfoComponent.spec.jsx
:nano WeatherInfoComponent.spec.jsx
Add the following content to the
WeatherInfoComponent.spec.jsx
file:import { test, expect } from '@playwright/experimental-ct-react'; import { WeatherComponent } from '../modules/WeatherInfoComponent'; test('WeatherInfo accepts name and value', async ({ mount }) => { const weatherInfo = { "coord": { "lon": 105.8412, "lat": 21.0245 }, "weather": [{ "id": 800, "main": "Clear", "description": "clear sky", "icon": "01n" }], "main": { "temp": 302.15, "pressure": 1003, "humidity": 35 }, "name": "Hanoi" }; const weatherComponent = await mount(); await expect(weatherComponent).toContainText('Hanoi'); });
Save and exit your file by pressing
CTRL+X
.You have now finished writing the test for WeatherInfoComponent. Next, you will run the CityComponent and WeatherInfoComponent tests for all three installed browsers.
Step 5 — Running the Component Tests
In this step, you will run the CityComponent and WeatherInfoComponent tests for all three installed browsers—Chromium, Firefox, and WebKit—to ensure that the two components work properly on those browsers.
First, navigate to the root project directory:
cd ../..
After running the command, you will be in the
react-component-testing-demo
folder. Then, run the following command to execute the tests:npm run test-ct
Playwright will run the two test files for all three browsers: Chromium, Firefox, and WebKit. You will get results similar to the following output:
Running 9 tests using 2 workers vite v3.2.5 building for production... ✓ 89 modules transformed. playwright/.cache/playwright/index.html 0.32 KiB playwright/.cache/assets/index.2b5442e2.js 313.68 KiB / gzip: 81.07 KiB 9 passed (12s) To open last HTML report run: npx playwright show-report
To view the report in GUI format, run the following command:
npx playwright show-report
Note: If you are executing these commands on a local machine that supports a graphical user interface (GUI) and have a browser like Chrome or Firefox already installed, the weather app will automatically open in your browser. However, if you are executing these commands on a remote server, you need to use port forwarding via SSH to open the app on your local machine.
In a new terminal, run the following command:
ssh -L 9223:localhost:9223 your_non_root_user@your_server_ip
You will now be able to access the test report from your local machine.
Reviewing the Test Report
The test report overview will display in your browser:
The test report is separated into the three different tests:
cityField accepts text input
,Click on Search button executes fetchWeather prop
, andWeatherInfo accepts name and value
, where each test displays the overall time the test took to run, as well as how long each browser’s test took to run.By clicking on each test—for example,
cityField accepts text input
—you will get the details of the time and the lines of code for each step in the test.The results indicate that the CityComponent test that checks whether the City input box accepts text as input ran successfully on Chromium. In the details section, the test execution steps will feature Before Hooks and After Hooks steps by default. The Before Hooks section is often used for initial setup, such as logging into the console or reading test data. After the test execution, the After Hooks section will often clean test data in the test environment.
You have now fully implemented and run the CityComponent and WeatherInfoComponent tests for your weather application and reviewed the test report to ensure that the two components work on Chromium, Firefox, and WebKit. You can check out the full source code for both the application and the tests on the main branch of the GitHub repository.
Conclusion
You have now used Playwright to implement component testing on a React-based weather app. First, you installed the necessary test dependencies for the weather app components CityComponent and WeatherInfoComponent. Then, you wrote and ran the component tests for the two components. Finally, you reviewed the test report in GUI format to ensure the components ran as expected.
To learn more about Playwright and other functionalities that it supports for component testing, visit the Playwright documentation.