Playwright is a free tool from Microsoft that makes testing websites easier. It lets you test on different browsers using several programming languages. With features like running tests without opening a browser window, testing multiple things at once, and checking network requests, Playwright is great for modern development. This playwright testing tutorial will help you set up Playwright, write and run tests, and manage them effectively. Whether you are just starting with Playwright or want to improve your testing skills. This playwright tutorial will show you how to use Playwright effectively.
Playwright is an open-source tool by Microsoft for testing web applications across different browsers like Chromium, Firefox, and WebKit. It works with languages like JavaScript, TypeScript, Python, C#, and Java, making it flexible for developers and testers. Playwright allows you to automate tests, run them faster in headless mode (without a browser window), and test several things at once. It also has powerful features like checking network requests and simulating different devices. This makes Playwright a great choice for ensuring web apps work well and are reliable for helping teams to test more efficiently. For those interested in learning more, a Playwright testing tutorial can guide you through using its features effectively, helping teams to test more efficiently.
Before diving into the technical details, let’s understand why the playwright framework is a game-changer in the world of automated testing:
Getting started with Playwright involves setting up your environment, installing Playwright, and writing your first test. Here is a quick playwright automation tutorial to help you get started:
Before you start, make sure you have Node.js installed on your machine. You can check if Node.js is installed by running the following command in your terminal:
node -v |
If Node.js is not installed, download and install it from here.
To install Playwright, run the following command in your terminal:
npm init playwright@latest |
This command will initialize a new project with Playwright, download the necessary binaries, and create a basic project structure.
After installation, you can create your first test. Here is an example of a simple test in this playwright testing tutorial:
const { test, expect } = require(‘@playwright/test’);
test(‘basic test’, async ({ page }) => { await page.goto(‘https://example.com’); const title = await page.title(); expect(title).toBe(‘Example Domain’); }); |
This test navigates to https://example.com, grabs the page title, and checks if it matches the Example Domain.
To run your test, use the following command:
npx playwright test |
This will execute the test and provide you with the results in the terminal.
The Playwright test runner is powerful and comes with many features such as parallel testing, automatic retries, and test fixtures. For a comprehensive guide on these features and how to use them effectively, check out the Playwright testing tutorial and the Playwright’s documentation.
Playwright also allows you to record tests, which can help you create tests quickly:
npx playwright codegen https://example.com |
This command opens a browser where you can interact with the website. The playwright will generate the corresponding code automatically.
By default, Playwright runs tests in Chromium. However, you can run tests in other browsers like Firefox or WebKit:
npx playwright test –project=firefox
npx playwright test –project=webkit |
Playwright can be easily integrated into your CI/CD pipelines. It supports a variety of CI providers such as GitHub Actions, Azure Pipelines, and more.
To dive deeper into Playwright, you can explore the following resources:
This playwright’s example should give you a good start with it.
You can reuse Playwright and Browser instances to improve performance. But it is better to run each test in a new BrowserContext. To keep the browser state separate as well as avoid issues between tests. For detailed guidance on this and other best practices, read this Playwright testing tutorial carefully.
In JUnit, you can set up Playwright and Browser in the @BeforeAll method and close them in @AfterAll. This way, all the tests share the same Browser, but each test gets its own BrowserContext and Page.
package org.example;
import com.microsoft.playwright.Browser; import com.microsoft.playwright.BrowserContext; import com.microsoft.playwright.Page; import com.microsoft.playwright.Playwright; import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; public class TestExample { // Shared between all tests in this class. static Playwright playwright; static Browser browser; // New instance for each test method. BrowserContext context; Page page; @BeforeAll static void launchBrowser() { playwright = Playwright.create(); browser = playwright.chromium().launch(); } @AfterAll static void closeBrowser() { playwright.close(); } @BeforeEach void createContextAndPage() { context = browser.newContext(); page = context.newPage(); } @AfterEach void closeContext() { context.close(); } @Test void shouldClickButton() { page.navigate(“data:text/html,<script>var result;</script><button onclick=’result=\”Clicked\”‘>Go</button>”); page.locator(“button”).click(); assertEquals(“Clicked”, page.evaluate(“result”)); } @Test void shouldCheckTheBox() { page.setContent(“<input id=’checkbox’ type=’checkbox’></input>”); page.locator(“input”).check(); assertTrue((Boolean) page.evaluate(“() => window[‘checkbox’].checked”)); } @Test void shouldSearchWiki() { page.navigate(“https://www.wikipedia.org/”); page.locator(“input[name=\”search\”]”).click(); page.locator(“input[name=\”search\”]”).fill(“playwright”); page.locator(“input[name=\”search\”]”).press(“Enter”); assertEquals(“https://en.wikipedia.org/wiki/Playwright”, page.url()); } } |
Check out the new JUnit integration that makes it easier to set up Playwright objects and other cool stuff automatically during testing.
By default, JUnit runs all tests one after the other on a single thread. Starting with JUnit 5.3, you can make tests run in parallel to save time. However, using the same Playwright objects in multiple threads isn’t safe. It is best to create a separate Playwright instance for each thread and only use it within that thread. So, here is in this playwright testing tutorial how you can set up multiple test classes to run in parallel.
Use the @TestInstance(TestInstance.Lifecycle.PER_CLASS) annotation in JUnit. To create a single instance of a test class for all its test methods (instead of creating a new instance for each method by default). You can store Playwright and Browser objects as instance fields, so they are shared between tests in that class. Each test class will have its own Playwright instance.
// Subclasses will inherit PER_CLASS behavior.
@TestInstance(TestInstance.Lifecycle.PER_CLASS) class TestFixtures { // Shared between all tests in the class. Playwright playwright; Browser browser; @BeforeAll void launchBrowser() { playwright = Playwright.create(); browser = playwright.chromium().launch(); } @AfterAll void closeBrowser() { playwright.close(); } // New instance for each test method. BrowserContext context; Page page; @BeforeEach void createContextAndPage() { context = browser.newContext(); page = context.newPage(); } @AfterEach void closeContext() { context.close(); } } class Test1 extends TestFixtures { @Test void shouldClickButton() { page.navigate(“data:text/html,<script>var result;</script><button onclick=’result=\”Clicked\”‘>Go</button>”); page.locator(“button”).click(); assertEquals(“Clicked”, page.evaluate(“result”)); } @Test void shouldCheckTheBox() { page.setContent(“<input id=’checkbox’ type=’checkbox’></input>”); page.locator(“input”).check(); assertTrue((Boolean) page.evaluate(“() => window[‘checkbox’].checked”)); } @Test void shouldSearchWiki() { page.navigate(“https://www.wikipedia.org/”); page.locator(“input[name=\”search\”]”).click(); page.locator(“input[name=\”search\”]”).fill(“playwright”); page.locator(“input[name=\”search\”]”).press(“Enter”); assertEquals(“https://en.wikipedia.org/wiki/Playwright”, page.url()); } } class Test2 extends TestFixtures { @Test void shouldReturnInnerHTML() { page.setContent(“<div>hello</div>”); assertEquals(“hello”, page.innerHTML(“css=div”)); } @Test void shouldClickButton() { Page popup = page.waitForPopup(() -> { page.evaluate(“window.open(‘about:blank’);”); }); assertEquals(“about:blank”, popup.url()); } } |
Set up JUnit to run tests within each class one after the other and run multiple classes at the same time on different threads. The number of threads should be half the number of CPU cores.
junit.jupiter.execution.parallel.enabled = true
junit.jupiter.execution.parallel.mode.default = same_thread junit.jupiter.execution.parallel.mode.classes.default = concurrent junit.jupiter.execution.parallel.config.strategy=dynamic junit.jupiter.execution.parallel.config.dynamic.factor=0.5 |
You have the option to utilize a Gradle build setup script, which can be written in Groovy or Kotlin.
plugins {
application id ‘java’ } repositories { mavenCentral() } dependencies { implementation ‘com.microsoft.playwright:playwright:1.46.0’ } application { mainClass = ‘org.example.App’ } // Usage: ./gradlew playwright –args=”help” task playwright(type: JavaExec) { classpath sourceSets.test.runtimeClasspath mainClass = ‘com.microsoft.playwright.CLI’ } test { useJUnitPlatform() } |
Tests can then be launched as follows:
./gradlew run |
Also, Playwright command line tools can be run with :
./gradlew playwright –args=”help” |
In TestNG, you can set up Playwright and Browser in the @BeforeClass method and close them in @AfterClass. This means all test methods will share the same Browser, but each test will have its own BrowserContext and Page. For a detailed walkthrough of these practices, focus on the Playwright testing tutorial carefully.
package org.example;
import com.microsoft.playwright.Browser; import com.microsoft.playwright.BrowserContext; import com.microsoft.playwright.Page; import com.microsoft.playwright.Playwright; import org.testng.annotations.*; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class TestExample { // Shared between all tests in this class. Playwright playwright; Browser browser; // New instance for each test method. BrowserContext context; Page page; @BeforeClass void launchBrowser() { playwright = Playwright.create(); browser = playwright.chromium().launch(); } @AfterClass void closeBrowser() { playwright.close(); } @BeforeMethod void createContextAndPage() { context = browser.newContext(); page = context.newPage(); } @AfterMethod void closeContext() { context.close(); } @Test void shouldClickButton() { page.navigate(“data:text/html,<script>var result;</script><button onclick=’result=\”Clicked\”‘>Go</button>”); page.locator(“button”).click(); assertEquals(“Clicked”, page.evaluate(“result”)); } @Test void shouldCheckTheBox() { page.setContent(“<input id=’checkbox’ type=’checkbox’></input>”); page.locator(“input”).check(); assertTrue((Boolean) page.evaluate(“() => window[‘checkbox’].checked”)); } @Test void shouldSearchWiki() { page.navigate(“https://www.wikipedia.org/”); page.locator(“input[name=\”search\”]”).click(); page.locator(“input[name=\”search\”]”).fill(“playwright”); page.locator(“input[name=\”search\”]”).press(“Enter”); assertEquals(“https://en.wikipedia.org/wiki/Playwright”, page.url()); } } |
Playwright can be used as part of a bigger automation system, which makes it useful for testing all aspects of software in the development and deployment process.
Setting Up CI/CD Integration: Playwright works well with CI/CD tools like Jenkins, CircleCI, and GitHub Actions. For GitHub Actions, just create a file named .github/workflows/playwright.yml to set it up:
name: Playwright Tests
on: [push] jobs: test: runs-on: ubuntu-latest steps: – uses: actions/checkout@v2 – name: Set up Node.js uses: actions/setup-node@v2 with: node-version: ’14’ – run: npm install – run: npx playwright install –with-deps – run: npm test |
Once everything is set up, your Playwright tests will run on their own every time you make changes to your code and save them in your online storage space.
This playwright testing tutorial mainly covers JavaScript, but Playwright also works with other languages like Python, C#, and Java.
Playwright provides Python developers with an interface that is similar to the one used in JavaScript.
pip install playwright |
from playwright.sync_api import sync_playwright
with sync_playwright() as p: browser = p.chromium.launch() page = browser.new_page() page.goto(‘https://example.com’) print(page.title()) # Outputs “Example Domain” browser.close() |
python example_test.py |
Playwright is compatible with various tools and libraries that enhance its functionality.
To ensure your Playwright tests are efficient and maintainable, follow these best practices:
When comparing Playwright to other testing frameworks, focus on features, how easy it is to use, and support for different browsers. As well as how well it integrates with other tools. So, here is a comparison of Playwright with some popular testing frameworks in this playwright testing tutorial:
2. API and Language Support
3. Parallel Execution
4. Auto-Waiting
5. Network Interception
2. Cross-Browser Support
3. API and Language Support
4. Testing Features
5. Test Execution and Reporting
1. Cross-Browser Support
2. API Features
3. Community and Ecosystem
1. Cross-Browser Support
2. API and Language Support
3. Parallel Execution
4. Test Reporting and Integration
While moving forward in this playwright automation tutorial it is important to know even with this robust framework, you might encounter issues. Here is how to troubleshoot common problems:
In conclusion, Playwright is a powerful tool for testing web applications, making running tests across different browsers easier. It works with multiple programming languages and integrates well with CI/CD tools. This playwright testing tutorial has walked you through setting up Playwright and running tests by using its features and best practices. As well as you will be able to test your web apps effectively. With more practice, you’ll be ready to tackle even the toughest testing challenges confidently.
Ans. The playwright is both a tool and a framework. It offers APIs for automating web testing, which is great for developers and QA engineers. It also includes a testing framework with features like test runners, parallel execution, and reporting, making it a complete solution for end-to-end testing.
Ans. Yes, Playwright needs coding. It is made for developers and QA engineers who can write code to automate web tests. But its API is easy to use and well-documented. So even people with less coding experience can use it.
Ans. How quickly you learn Playwright depends on your background. If you know similar tools like Selenium or Cypress, you might get good at Playwright in a week. In fact, for beginners, it could take a couple of weeks to learn the basics and about a month to handle more complex tests.
About The Author:
The IoT Academy as a reputed ed-tech training institute is imparting online / Offline training in emerging technologies such as Data Science, Machine Learning, IoT, Deep Learning, and more. We believe in making revolutionary attempt in changing the course of making online education accessible and dynamic.