Playwright Automation Framework: Tutorial [2026]
Related Product On This Page What is Playwright?Feature
Related Product
- What is Playwright?
- Features of Playwright Automation
- Why choose Playwright Automation?
- Growing Popularity of Playwright Framework
- Getting Started with Playwright Setup
- How to Install and run Playwright Test Script
- Playwright Testing on BrowserStack
- How to Use Playwright with Java in Eclipse
- Playwright JavaScript example
- Important Playwright Concepts
- Is Playwright better than Selenium and Cypress?
- How to Integrate Playwright with CI/CD Tools
- Why run Playwright Automation Tests on BrowserStack Real Device Cloud?
- Utile Resources for Playwright
Playwright Automation Framework: Tutorial [2026]
What if you could run end-to-end exam across browsers in bit — without the flaky failure or decelerate setups most frameworks sputter with? That ’ s exactly what Playwright delivers.
Built by Microsoft, Playwright has speedily become a favourite among QA engineers and developers for its speeding, reliability, and versatility. In fact, with over 45 % of QA squad now automating the majority of their testing efforts, frameworks like Playwright are driving the succeeding undulation of smart, scalable automation.
Overwhelmed by Playwright setup
This tutorial, walks you through everything from frame-up to boost capacity — including parallel examination, API substantiation, and handling dynamic web elements — so you can build fast, more reliable pipelines and deliver high-quality software with self-assurance.
Learn in particular about Playwright automation in this usher covering the features, architecture, advantages, restriction, and more.
What is Playwright?
Playwrightis an open-source tryout automation library initially developed by Microsoft contributors. It endorse programming languages like Java, Python, C #, and NodeJS. Playwright comes with Apache 2.0 License and is near popular with NodeJS with Javascript/Typescript. This Playwright tutorial will help set up NodeJS apply Visual Studio Code.
Features of Playwright Automation
Here are the main features of Playwright Automation:
- : Playwright offers cross-browser testing potentiality and supports browser like Chromium, Firefox, and WebKit with a individual API.
- Multi-Language Support:Playwright supports JavaScript, TypeScript, Java, Python, and .NET.
- Auto-Waiting:The open-source framework waits automatically for elements to be ready
- Headless and Headed Modes: Run tests in visible or headless mode efficiently.
- Mobile and Device Emulation:Can seamlessly emulate devices, screen size and geolocation.
- Network Interception and Mocking:Playwright supports the interception of API shout and mocks responses for improved test control.
- Built-in Test Generator:Record actions to auto-generate code for tryout scripts.
- Visual and Screenshot Testing:Playwright supports visual and screenshot test helping you capture full-page screenshots, element snapshots, and video transcription.
Read More:
Why choose Playwright Automation?
Though Playwright is new to the grocery, we can hardly lean the limitations as it back multiple language. People who want to migrate from Selenium to Playwright can do it cursorily since Playwright support C #, Java, and Python. Programming languages are not a barrier. Playwright & # 8217; s first release was in January 2020, and it has gained much popularity ever since.
- It leverage the DevTools protocol to write knock-down, stable automated trial.
- It can see into and check the browser rather than trust on a middle translation level; it allows for the model of more insightful and relevant user scenarios.
To take your Playwright mechanisation to the next level and check optimum examination execution, it & # 8217; s indispensable to have expert insights.
Get Expert QA Guidance Today
Schedule a call with BrowserStack QA specialists to discuss your testing challenge, automation strategies, and instrument integrations. Gain actionable insights tailored to your projects and ensure faster, more reliable package delivery.
Overwhelmed by Playwright setup
Growing Popularity of Playwright Framework
As of 2025, the current snapshot of Microsoft Playwright onGithub:
- Fighting Users: 432k
- Forks(copy of a repository that you grapple): 4.9k
- Releases: 155 (This shows how active they are in fixing and relinquish new feature)
NPM Trendsof Playwright Framework:
- Weekly Downloads: 12 million
Advantages of Playwright Automation
Playwright contributors are highly active in releasing new lineament every month, which are listed below:
- Easy Setup and Configuration:Being a, it just needs a configuration as the installation doesn ’ t take much clip. Depending on the language we use with Playwright, the installing steps might modify
- Multi-Browser Support:Chromium family browser (Chrome, Edge), Webkit (Safari), and Firefox are all indorse.
- Multi-Language Support:Playwright supports Java, C #, Python, Javascript/ Typescript making it a democratic alternative. Most of the mod open-source test mechanization frameworks miss this feature.
- Types of Testing:Playwright back Functional, End to End, and API Testing. With a third-party plugin, Playwright can be incorporate with.
- Parallel Browser Testing:Playwright too supports the executing of simultaneous tests (AKA) through Browser Context and can run parallel tests with multiple browser. This scale up testing and comes in handy when multiple web page must be essay simultaneously.
- Support for Multiple Tab/Browser Window:Playwright supports multi-tab and multi-window. Some test cases must verify the scenario by found a new window and returning to the parent window. Playwright endorse all different types of test cases.
- Built-in Reporters:Playwright framework, by default, comes with many valuable newsperson like List, Dot, Line, JSON, JUnit, and HTML Reporters. The exciting constituent is that with Playwright, one can create custom reporters. Playwright besides supports third-party reporter Allure Report.
- Typescript Support out of the box:Zero constellation is required for typescript language support as it understands your typescript and javascript code.
- CI/CD Integration Support:Playwright supports CI/CD integration. It even provides docker images for some language bindings.
- Debugging Tools Support:Playwright essay support different debugging options make it developer-friendly. Some debugging options are Playwright Inspector, VSCode Debugger, Browser Developer Tools, and Trace Viewers Console Logs.
Limitations of Playwright Automation
- Playwright is new, and it ’ s still evolving—scope for advance.
- No Support for IE11
- Playwright doesn ’ t support Native Mobile Apps
- Though Playwright documentation is first-class, we can not expect much regarding community support. Since Playwright is new to the market user base is still grow.
Getting Started with Playwright Setup
This Playwright tutorial explains how to set up with NodeJS easily.
Pre-Requisites:
- Install Visual Studio Code: Downloadand Install Visual Studio Code (VSCode).
- Install NodeJS:Downloadand Install Node JS
How to Install and run Playwright Test Script
Follow the below steps to install and run Playwright Test Script:
Step 1:Create a fresh new directory (ex: PlaywrightDemo) in VSCode
Step 2:Open Directory in Visual Studio Code. From VS code,
Click on File & gt; Open Folder & gt; Choose freshly Created Folder (PlaywrightDemo)
Step 3:From the VS Code, Click on Terminal Menu & gt; Click on New Terminal
Step 4:Enter the below dictation to start the Playwright facility
npm init playwright @ up-to-the-minute
Note:The above command ask a set of questions. Please provide appropriate inputs. In this tutorial, we are employtypescript lyric.
The above dictation does the following operation:
- Creates Package.json
- Installs npm library
- Sets up introductory Files and Folders
- trial folder:This folder contains literal test scripts. By default, an example.spec.ts file will be created inside this folder.
- .gitignore:This file helps if you are using git repository
- package.json and package-lock.json:This file helps to trail dependencies, create a shortcut for running tests, etc.
- playwright.config.ts:This is the planetary configuration file for the Playwright, which you can configure with available options.
Step 5: Install Browsers
However, Playwright is configured to run on existing browser, which might create issues while running tests, so it is recommended to use the Playwright browser. Using the below bid, you can install all different browsers in Playwright.
npx playwright install
The above bid install the Playwright variant of Chromium, Firefox, and Webkit browser.
Step 6: Create the maiden Playwright test
Navigate inside the exam folder and make a test spec file ex:demo.spec.ts
Let ’ s start a test case with the below scenario
Scenario:
- Navigate to
- Click on Sign In
- Enter wrong credentials
- Verify Error Message is displayed or not.
The demo.spec.tsis our Playwright test hand as follows
//demo.spec.ts significance {test, expect, Page} from ' @ playwright/test '; test.beforeEach (async ({page}) = & gt; {await page.goto ('https: //www.browserstack.com/ ');}); test.describe ('Demo Test ', () = & gt; {test ('Verify Login Error Message ', async ({page}) = & gt; {await page.waitForSelector ('text=Sign in ', {province: 'visible '}); wait page.locator ('text=Sign in ') .first () .click (); await page.waitForSelector (' # user_email_login ') await page.locator (' # user_email_login ') .type ('example1 @ example.com '); await page.locator (' # user_password ') .type ('examplepassword '); await page.locator (' # user_submit ') .click (); const errorMessage = await (await page.locator (`` //input [@ id='user_password '] / .. /div [@ class='error-msg '] '') .textContent ()) .trim (); console.log (`` Browserstack Login Error Message: `` +errorMessage); await (errorMessage) .toBe ('Invalid password ');});});Step 7: Execute Playwright Test Script
As discuss above, during installation, Playwright createsplaywright.config.ts(playwright.config.ts is the worldwide shape file) which will have some settings. By nonremittal, the global configuration curb the value to run on all the browsers. It runs on all three different browsers when you execute the Playwright test. We don ’ t need it, so we need to remove that option.
- Navigate toplaywright.config.ts. Comment the option which starts withprojects: [
If you are find to do the above, copy and paste the below line of code toplaywright.config.ts
//playwright.config.ts import type {PlaywrightTestConfig} from ' @ playwright/test '; const config: PlaywrightTestConfig = {testDir: './tests ', timeout: 30 * 1000, expect: {timeout: 5000}, reporter: 'html ', use: {actionTimeout: 0, trace: 'on-first-retry ',},}; export default config;So, you have configured theplaywright.config.ts, we are all set to execute the first Playwright test playscript.
Execute Playwright Spec using the below command
npx playwright test demo.spec.ts –headed
Let ’ s understand the above command:
- We are qualify which test file we need to run i.e.demo.spec.ts. Do not mention any spec file name if you want to run all the specification files inside the tests folder, do not mention any spec file gens.
- Playwright runs in headless mode by default, so we specify the–headedto run on headed mode.
- We are not mentioning any browser name; by default, the Playwright test runs in theChromium browser
Once you action the above command, the Playwright examination start executing in the Chromium browser.
Step 8: View the story
In our playwright.config.ts, we specify the HTML account, so after executing the Playwright test, the HTML report gets generated automatically in theplaywright-report folder.
To view generated HTML study merely type:
npx playwright show-report
Overwhelmed by Playwright setup
Playwright Testing on BrowserStack
One can run all your tests on BrowserStack as good. Follow the step below to run the sample tests in this repository:
Step 1:Clone this repository using git ringer
Step 2:Go inside the directory playwright-test expend
cd playwright-test
Step 3: Install the dependency using
npm install
Step 4: Put in your credentials in the filefixtures.jsin the caps component.
Step 5: To run your tests on BrowserStack, you must ensure you correctly configured the projects in theplaywright.config.js file.
Step 6: Run the sample test script using the
npm test
Pro tip: Tools like SUSA can handle this autonomously — upload your app and get results without writing a single test script.
This command runs all the trial inside the trial directory across five browsers in BrowserStack.
Step 7: If you want to test against localhost or other private websites, run the sample exam script use the command
npm run test: local
Step 8: To run your tests topically, you must configure the projects without the name@ browserstack in playwright.config.js file.
For consummate details, visit the.
How to Use Playwright with Java in Eclipse
Playwright support Java through its official client. Here & # 8217; s how you can use it with Eclipse:
1. Install Java & amp; Eclipse:
Ensure you hold installed Java JDK 11 or high. Also install Eclipse IDE for Java Developers.
2. Set Up Maven Project in Eclipse
- Exposed Eclipse. Then create a new Maven Project.
- Add the given dependency to your pom.xml:
& lt; dependency & gt; & lt; groupId & gt; com.microsoft.playwright & lt; /groupId & gt; & lt; artifactId & gt; playwright & lt; /artifactId & gt; & lt; version & gt; 1.44.0 & lt; /version & gt; & lt;! -- Check for late version -- & gt; & lt; /dependency & gt;
3. Install Playwright Browsers
Once you purpose the dependence, run the following in your terminal to download Chromium, Firefox, and WebKit browsers for Playwright.
mvn exec: java -e -Dexec.mainClass=com.microsoft.playwright.CLI -Dexec.args= '' install ''
4. Sample Test
Create a class like PlaywrightTest.java in src/main/java:
import com.microsoft.playwright. *; public stratum PlaywrightTest {public motionless void chief (String [] args) {try (Playwright playwright = Playwright.create ()) {Browser browser = playwright.chromium () .launch (new BrowserType.LaunchOptions () .setHeadless (false)); Page page = browser.newPage (); page.navigate (`` https: //example.com ''); System.out.println (`` Page title: `` + page.title ());}}}5. Run the exam
- Right-click the file & gt; Run As & gt; Java Application.
- This will found a browser, open the page, and print the title.
Playwright JavaScript example
Here ’ s a Playwright JavaScript example to open a page and print the title:
// playwright-example.js const {chromium} = require ('playwright '); // Or 'firefox ' or 'webkit' (async () = & gt; {// Launch browser const browser = await chromium.launch ({headless: false}); // Set to true for headless mode const context = await browser.newContext (); const page = await context.newPage (); // Navigate to a website await page.goto ('https: //example.com '); // Print the page title const rubric = await page.title (); console.log (` Page title: $ {title} `); // Close browser await browser.close ();}) ();You can run this by:
1. Initializing a project:
npm init -y
2. Install Playwright
npm install -D playwright
3. Run the Script
Read More:
Important Playwright Concepts
Understanding Playwright become importantly easier when the core concepts behind its performance model and tooling are open. These fundamentals forthwith influence how stable, scalable, and maintainable Playwright test suites are built.
Playwright render rich execution study that include test status, timings, screenshots, videos, and traces. Reports can be configured for local debugging or CI integration use built-in newsman.
// playwright.config.ts import {defineConfig} from ' @ playwright/test '; exportation nonpayment defineConfig ({reporter: [['html ', {open: 'never '}], ['junit ', {outputFile: 'results.xml '}]],});Playwright Inspector
The Inspector enable step-by-step debugging by pausing execution and discover selectors, DOM province, and actions in existent clip during a examination run.
PWDEBUG=1 npx playwright test
Playwright Inputs and Buttons
Playwright handles form remark and push using user-like actions that automatically wait for elements to turn actionable.
await page.getByLabel ('Email ') .fill ('qa @ example.com '); await page.getByRole ('button ', {name: 'Sign in '}) .click ();Playwright Functions and Selectors
Multiple engines and custom picker logic helper target element dependably even when UI structure change.
await page.locator ('data-test-id=checkout ') .click (); await page.getByRole ('link ', {name: /pricing/i}) .click ();Playwright Alerts and Dropdowns
JavaScript dialog are captured through event listeners, while dropdowns can be plow using native selection APIs.
page.on ('dialog ', d = & gt; d.accept ()); await page.locator ('select # state ') .selectOption ('IN ');Playwright Frames and Windows
New tabs and window are managed through events, eliminating the want for manual window handle shift.
const popup = await page.waitForEvent ('popup '); await page.getByRole ('link ', {name: 'Open help '}) .click (); await popup.getByText ('Contact ') .click ();Read More:
Playwright iFrames
iFrames are accessed apply scoped frame locators that wait for the frame to lade before interaction.
await page.frameLocator (' # payment-iframe ') .getByRole ('button ', {gens: 'Pay '}) .click ();Locators dynamically re-resolve element at action clip, improving stability across UI updates.
const row = page.getByRole ('row ', {name: /invoice # 123/i}); await row.getByRole ('button ', {gens: 'Download '}) .click ();Playwright Date Pickers
Date inputs can be examine either by interacting with the calendar UI or by setting values directly when supported.
await page.locator ('input [name= '' dob ''] ') .fill ('1995-12-26 ');Assertions mechanically retry until weather are met, reducing the demand for explicit waits.
await expect (page.getByRole ('heading ', {name: 'Dashboard '})) .toBeVisible (); await expect (page) .toHaveURL (/\/dashboard $ /);The Page Object Model encapsulates page behavior into reclaimable classes, improving readability and maintenance.
class LoginPage {constructor (individual page) {} async login (e-mail: twine, pwd: string) {await this.page.getByLabel ('Email ') .fill (email); await this.page.getByLabel ('Password ') .fill (pwd); await this.page.getByRole ('button ', {gens: 'Sign in '}) .click ();}}Scrolling can be triggered explicitly to interact with elements outside the viewport.
await page.getByText ('Load more ') .scrollIntoViewIfNeeded ();Playwright detent () Method
The clink () API expect for visibility and stableness before interaction, with option to override nonpayment.
await page.locator (' # submit ') .click ({force: true});Navigation waits ascertain page transitions complete before assertions execute.
await Promise.all ([page.waitForNavigation (), page.getByRole ('link ', {name: 'Next '}) .click (),]);Timeouts can be delimitate globally or per activity to equilibrise speeding and reliability.
page.setDefaultTimeout (10_000); page.setDefaultNavigationTimeout (30_000);
Playwright Tags
Tags enable selective execution of tryout ground on purpose or environment.
test ('checkout works @ smoking ', async ({page}) = & gt; {});Docker images ply a coherent runtime for executing Playwright tests in CI pipeline.
docker run -- rm -v `` $ PWD '': /work -w /work mcr.microsoft.com/playwright \ npx playwright exam
Visual equivalence detect unintended UI changes by comparing screenshots across runs.
await expect (page) .toHaveScreenshot ('home.png ');Playwright can extract datum from JavaScript-heavy pages by executing code after content loads.
const titles = await page.locator ('h2 ') .allTextContents ();JavaScript render direct access to all Playwright APIs and integrates easily with frontend tooling.
const {test, expect} = require (' @ playwright/test '); test ('title ', async ({page}) = & gt; {await page.goto ('https: //example.com ');});TypeScript adds stable typewriting and better editor support for large automation suites.
import {test} from ' @ playwright/test '; test ('has heading ', async ({page}) = & gt; {await page.goto ('https: //example.com ');});Playwright Python
exposes the same core mechanisation features expend Pythonic syntax.
from playwright.sync_api import sync_playwright with sync_playwright () as p: page = p.chromium.launch () .new_page () page.goto (`` https: //example.com '')
Component examine validates UI components in isolation without bunk the full application.
import {test} from ' @ playwright/experimental-ct-react '; import Button from './Button '; test ('renders ', async ({rise}) = & gt; {await mount (& lt; Button & gt; Save & lt; /Button & gt;);});API testing enables direct validation of backend endpoints alongside UI exam.
const res = await request.get ('https: //api.example.com/health '); expect (res.ok ()) .toBeTruthy ();Playwright Headless Testing
style meliorate execution speeding and is usually used in CI environments.
npx playwright examination -- headed=false
Sharding distributes test across multiple workers or machines to reduce executing time.
npx playwright test -- shard=1/4
Auto Heal in Playwright
Playwright understate maintenance through resilient locators and retry mechanisms rather of opaque self-healing logic.
await page.getByRole ('button ', {name: 'Continue '}) .click ();adds to Playwright by mechanically adapting to UI change at runtime. When locators break due to DOM updates, BrowserStack intelligently identifies the near matching elements and continues execution, reducing test failures and care effort without command alteration to existing Playwright test code.
Is Playwright better than Selenium and Cypress?
Choosing between Playwright,, and depends on your project requirements. All three frameworks have their strength and impuissance.
- Playwright is a new tool, so you may not find extensive community support or online resources as compared to Selenium and Cypress, which are more accomplished.
- Playwright works well at automating complex web applications and integrates seamlessly with CI/CD pipelines.
- Selenium offers extensive browser support, community support, along with greater scalability, making it a great choice for enterprise-level or legacy projects.
- Cypress proffer a unseamed developer experience for frontend testing but lack cross-browser testing capabilities beyond Chromium.
Overall, Playwright is a outstanding instrument for testing modernistic, dynamic apps while Cypress and Selenium fulfills broader use cases and provides better community support.
Read More:
How to Integrate Playwright with CI/CD Tools
Integrating Playwright into your CI/CD pipeline alleviate the execution of machine-controlled tests with every code change. Here & # 8217; s a general method to integrate Playwright with popular:
Introductory Setup
Make sure the project has playwright installed via npm. Als, the test should be located in a booklet like /tests. You should also have a test handwriting in package.json:
`` scripts '': {'' test '': `` npx playwright test ''}Install Playwright browsers (needed for CI)
npx playwright install -- with-deps
Example with
pipeline {agent any stages {phase ('Install ') {steps {sh 'npm ci' sh 'npx playwright install -- with-deps'}} level ('Test ') {steps {sh 'npx playwright test'}}}}Why run Playwright Automation Tests on BrowserStack Real Device Cloud?
You should run Playwright Automation Tests on a real device cloud like for below reasons:
- Realistic Testing Conditions:Real gimmick clouds provide entree to a broad spectrum of devices and environments, ensuring tests reflect genuine user conditions accurately.
- Enhanced Security:Maintained with high security criterion, real device clouds volunteer secure, isolated testing environments, minimizing data rift jeopardy.
- Broad Browser and OS Coverage:Helps name compatibility subject across various browsers and operating systems, enhancing user experience.
- Performance Insights:Real devices give authentic performance data necessary for optimizing application responsiveness.
- Scalability and Accessibility:Facilitates scalable and accessible examination, worthy for distributed teams.
- CI/CD Integration:Integrates smoothly with CI/CD pipelines for uninterrupted testing and early issue catching.
- Cost-Effectiveness:Although initially more pricey, it saves on long-term expenses relate to fixing and support.
Conclusion
Playwright is a solid test mechanisation model that allows you to do across major browsers. It is equipped with multiple features, such as resiliency, auto-wait, capturing exam trace, and so on, supported with BrowserStack.
- BrowserStack ’ s existent twist cloud provides 3500+ existent browsers and device for instant, on-demand examination.
- The cloud also provides with popular CI/CD puppet such as Jira, Jenkins, TeamCity, Travis CI, and more.
- Additionally, in-built let testers name and resolve bugs immediately.
Run hundreds of in parallel in bit. Focus on essay & # 8211; not test infrastructure & # 8211; with zero setup and care.
Utile Resources for Playwright
Tool Comparisons:
On This Page
- What is Playwright?
- Features of Playwright Automation
- Why choose Playwright Automation?
- Growing Popularity of Playwright Framework
- Getting Started with Playwright Setup
- How to Install and run Playwright Test Script
- Playwright Testing on BrowserStack
- How to Use Playwright with Java in Eclipse
- Playwright JavaScript example
- Important Playwright Concepts
- Is Playwright better than Selenium and Cypress?
- How to Integrate Playwright with CI/CD Tools
- Why run Playwright Automation Tests on BrowserStack Real Device Cloud?
- Utilitarian Resources for Playwright
# Ask-and-Contributeabout this topic with our Discord community.
Related Guides
Automate This With SUSA
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.
Try SUSA FreeTest Your App Autonomously
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.
Try SUSA Free