Playwright Interview Questions with Answers Section
1: Playwright Basics 1. What is Playwright? Answer: Playwright is an open-source automation framework by Microsoft that is used for end-to-end testing of web applications. It supports multiple browsers (Chromium, Firefox, and WebKit) and allows testing in multiple languages (JavaScript, TypeScript, Python, C#, and Java).
2. How do you install Playwright? Answer: You can install Playwright using npm: Or install it separately:
3. How do you launch a browser in Playwright? Answer:
4. What browsers does Playwright support? Answer: Playwright supports: ● Chromium (Google Chrome, Microsoft Edge) ● Firefox ● WebKit (Safari) Anshul Agarwal
2: Playwright Advanced Concepts
5. How do you handle authentication in Playwright? Answer:
6. How do you take screenshots in Playwright? Answer:
7. How do you test API responses using Playwright?
21. How do you disable JavaScript in Playwright? Answer: 22. How do you validate an element's CSS properties? Answer: const color = await page.locator('selector').evaluate(el => getComputedStyle(el).color); 23. How do you test dark mode in Playwright? Answer: 24. How do you emulate touch devices? Answer: 25. How do you handle SSL errors? Answer: Anshul Agarwal https://www.linkedin.com/in/anshulagarwal30 Section 3: More Advanced Playwright Concepts 26. How do you validate tooltips in Playwright? Answer: 27. How do you interact with shadow DOM elements in Playwright? Answer: 28. How do you handle geolocation testing in Playwright? Answer: 29. How do you test responsiveness in Playwright? Answer: 30. How do you block requests in Playwright? Answer: Anshul Agarwal https://www.linkedin.com/in/anshulagarwal30 31. How do you handle keyboard events in Playwright? Answer: 32. How do you handle mouse hover in Playwright? Answer: 33. How do you slow down execution in Playwright for debugging? Answer: 34. How do you interact with modals in Playwright? Answer: 35. How do you validate console logs in Playwright? Answer: Anshul Agarwal https://www.linkedin.com/in/anshulagarwal30 36. How do you handle downloads in Playwright? Answer: 37. How do you test drag-and-drop functionality in Playwright? Answer: 38. How do you validate text content in Playwright? Answer: 39. How do you test auto-complete dropdowns in Playwright? Answer: 40. How do you check network request responses in Playwright? Answer: const response = await page.waitForResponse(response => response.url().includes('api-endpoint')); console.log(await response.json()); Anshul Agarwal https://www.linkedin.com/in/anshulagarwal30 41. How do you handle authentication popups in Playwright? Answer: 42. How do you capture full-page screenshots in Playwright? Answer: 43. How do you disable JavaScript while testing in Playwright? Answer: 44. How do you validate CSS properties of an element in Playwright? Answer: const color = await page.locator('selector').evaluate(el => getComputedStyle(el).color); console.log(color); 45. How do you test dark mode in Playwright? Answer: 46. How do you emulate a touch device in Playwright? Answer: Anshul Agarwal https://www.linkedin.com/in/anshulagarwal30 47. How do you handle SSL errors in Playwright? Answer: 48. How do you simulate a slow network in Playwright? Answer: 49. How do you check if an element is visible in Playwright? Answer: 50. How do you get the count of elements matching a selector? Answer: 51. How do you wait for an API response in Playwright? Answer: const response = await page.waitForResponse(response => response.url().includes('api-endpoint')); console.log(await response.json()); 52. How do you scroll to an element in Playwright? Answer: Anshul Agarwal https://www.linkedin.com/in/anshulagarwal30 53. How do you interact with an iframe in Playwright? Answer: 54. How do you simulate mobile gestures in Playwright? Answer: 55. How do you check local storage values in Playwright? Answer: 56. How do you handle right-click context menus in Playwright? Answer: 57. How do you test a webpage in offline mode using Playwright? Answer: 58. How do you use environment variables in Playwright tests? Answer: Anshul Agarwal https://www.linkedin.com/in/anshulagarwal30 59. How do you execute JavaScript code inside Playwright? Answer: 60. How do you automate form submission in Playwright? Answer: Section 4: Even More Advanced Playwright Concepts 61. How do you clear cookies in Playwright? Answer: 62. How do you assert a page title in Playwright? Answer: 63. How do you test a redirect in Playwright? Answer: Anshul Agarwal https://www.linkedin.com/in/anshulagarwal30 64. How do you interact with Shadow DOM elements? Answer: const shadowElement = await page.locator('shadow-host').shadowRoot().locator('inner-element'); await shadowElement.click(); 65. How do you test lazy-loaded elements in Playwright? Answer: 66. How do you capture console errors in Playwright? Answer: 67. How do you perform hover actions in Playwright? Answer: 68. How do you assert page load performance in Playwright? Answer: const perfTiming = await page.evaluate(() => JSON.stringify(window.performance.timing)); console.log(perfTiming); 69. How do you handle browser console logs in Playwright? Answer: Anshul Agarwal https://www.linkedin.com/in/anshulagarwal30 70. How do you block specific requests in Playwright? Answer: 71. How do you test download functionality in Playwright? Answer: 72. How do you test page reloads in Playwright? Answer: 73. How do you wait for multiple requests in Playwright? Answer: 74. How do you run Playwright tests in parallel? Answer: Anshul Agarwal https://www.linkedin.com/in/anshulagarwal30 75. How do you close a specific tab in Playwright? Answer: 76. How do you retrieve network request headers in Playwright? Answer: 77. How do you validate a text inside an element in Playwright? Answer: 78. How do you generate HTML reports from Playwright tests? Answer: 79. How do you use Playwright with Cucumber? Answer: 80. How do you wait for an element to disappear? Answer: Anshul Agarwal https://www.linkedin.com/in/anshulagarwal30 81. How do you check if an element is disabled? Answer: 82. How do you handle keyboard shortcuts in Playwright? Answer: 83. How do you test web components using Playwright? Answer: 84. How do you disable animations in Playwright? Answer: 85. How do you automate Google authentication in Playwright? Answer: 86. How do you handle reCAPTCHA in Playwright? Answer: Anshul Agarwal https://www.linkedin.com/in/anshulagarwal30 87. How do you test scrolling behavior in Playwright? Answer: 88. How do you use Playwright to check accessibility compliance? Answer: 89. How do you validate text inside an input field? Answer: 90. How do you handle dynamically loaded elements? Answer:
What is Playwright, and how is it different from other automation tools like Selenium?
Ans. Playwright is an open-source testing framework developed by Microsoft that enables reliable end-to-end testing for modern web apps. It supports multiple browser engines (Chromium, Firefox, and WebKit), headless execution, and cross-browser testing. Key differences from Selenium include:
Supports Multiple Languages: While Selenium supports Java, C#, Python, etc., Playwright works with JavaScript, TypeScript, Python, C#, and Java.
Out-of-the-box Multi-browser Support: Playwright offers native support for Chromium, Firefox, and WebKit, while Selenium uses browser drivers.
Auto-Waiting: Playwright automatically waits for elements to be ready for interaction (click, type, etc.), reducing flakiness.
2. How do you install Playwright in a Node.js project?
Ans. To install Playwright, you can use the npm package manager:
npm install @playwright/test
Once installed, you can run your Playwright tests using:
npx playwright test
3. How do you launch a browser and open a webpage using Playwright?
Ans. To launch a browser and open a webpage, you can use the following code:
const { chromium } = require('playwright');
(async () => { const browser = await chromium.launch({ headless: false }); // Launch the browser in non-headless mode const page = await browser.newPage(); await page.goto('https://example.com'); // Navigate to the website console.log(await page.title()); // Print the page title await browser.close(); // Close the browser })();
4. How do you handle dropdowns in Playwright?
Ans. You can select options from a dropdown using the selectOption method:
await page.selectOption('#dropdown_id', 'value1'); // Select the option by value
8. How do you wait for an element to be visible or clickable?
Ans. Playwright automatically waits for elements to be visible and ready to interact. However, you can explicitly wait for an element with conditions:
await page.waitForSelector('#element', { state: 'visible' }); // Wait for element to be visible await page.click('#element'); // Click the element once visible
For clickability:
await page.waitForSelector('#button', { state: 'attached' }); // Ensure element is attached to DOM await page.click('#button');
9. How do you perform parallel testing in Playwright?
Ans. Playwright provides built-in support for parallel test execution. You can specify the number of workers when running tests:
npx playwright test --workers=4
Alternatively, you can set this up in the playwright.config.js file:
How do you handle dynamic content the Playwright way?
Dynamic content is handled using locator assertions, network waiting, and proper synchronization rather than manual delays.
What are common anti-patterns that cause flaky tests?
Common issues include using static waits, relying on brittle selectors, sharing test data, and depending on execution order.
3. Locator assertions vs raw values—what do you prefer and why?
Locator-based assertions are preferred because they auto-wait and stay connected to the DOM. Raw value checks are more fragile and timing-dependent.
How are Playwright assertions designed to reduce flaky checks?
Playwright assertions automatically retry until the condition is met or a timeout occurs. This makes them more reliable than immediate value comparisons.
1. How do you handle waits properly in Playwright?
Instead of using static waits or sleep, Playwright encourages using locator-based assertions with expect. This waits dynamically until the expected condition is met.
How do you handle iframes in Playwright?
Playwright provides frame-specific locators to interact with elements inside iframes. Handling frames explicitly avoids flaky behavior caused by context switching.
3. How do you write resilient locators instead of brittle ones?
Resilient locators use roles, accessible names, text, or test IDs. These are more stable than CSS or XPath selectors, which often break when UI structure changes.
What is auto-waiting, and how does it reduce flakiness?
Auto-waiting ensures that elements are visible, enabled, and stable before any action or assertion is performed. This removes the need for explicit waits and reduces flaky failures caused by timing issues.
5. What are locators, and why are they central in Playwright?
Locators are Playwright’s core abstraction for finding and interacting with elements. They automatically wait for elements to be ready and re-query the DOM, which makes tests more stable than traditional selectors.
1. How do you organize tests in a Playwright project?
Tests are typically organized into spec files, shared fixtures, utility helpers, and page objects. This structure improves readability, reusability, and long-term maintenance of the automation framework.
2. How do you control headless/headed mode and baseURL?
Headless or headed mode can be configured globally or overridden via CLI. The baseURL is defined in config so tests can use relative paths, improving readability and making environment switching easier.
3. What are “projects” in Playwright config, and why use them?
Projects allow you to define multiple test environments within the same test suite. For example, you can create projects for Chromium, Firefox, mobile viewports, or different user roles. This avoids duplication and improves coverage.
4. What is playwright.config, and what do you typically configure there?
The playwright.config file controls how tests run. Common configurations include browser projects, baseURL, timeouts, retries, reporters, parallel workers, screenshots, videos, and trace settings. Centralized configuration helps maintain consistency across environments.
Playwright Debugging Toolkit Interview Questions
1. How does the HTML reporter work?
The HTML reporter generates a detailed test report and opens automatically after local runs, showing failures, traces, and artifacts.
2. How do you enable traces for CI failures?
Traces can be enabled conditionally in config to capture data only for failed retries, keeping CI runs efficient.
3. What is Trace Viewer and what does a trace contain?
Trace Viewer captures screenshots, DOM snapshots, network activity, and actions. It allows replaying failed tests visually.
4. How do you debug failing tests using Playwright Inspector?
Playwright Inspector allows step-by-step execution, live DOM inspection, and locator validation during test runs.
Playwright Fixtures, Hooks & Test Isolation Interview Questions
1. How do you create a custom fixture like a logged-in page?
Custom fixtures can be created by extending the base test and adding setup logic such as login steps. This avoids repeating login code across tests.
2. What’s the difference between fixtures and beforeEach hooks?
Fixtures are more flexible, composable, and scoped compared to traditional hooks. They allow dependency injection rather than shared mutable state.
3. How does fixture isolation work between tests?
Each test gets its own isolated environment by default. This ensures that actions in one test do not affect others, making parallel execution safer.
4. What are fixtures in Playwright Test and why are they useful?
Fixtures provide a clean way to set up and tear down test dependencies such as pages, contexts, or test data. They improve reuse and enforce test isolation.
Playwright Fundamental Interview Question Answer
1. What is Playwright, and why do teams choose it for E2E testing?
Playwright is an open-source automation framework developed by Microsoft for end-to-end testing of web applications. Teams choose Playwright because it offers built-in auto-waiting, fast execution, reliable locators, parallel execution, and strong debugging tools. Unlike older tools, Playwright reduces flaky tests and works consistently across modern browsers.
2. Playwright vs Selenium: What changes in approach?
Compared to Selenium, Playwright offers auto-waiting, modern locator strategies, faster execution, and better isolation using browser contexts. Testers focus less on manual waits and more on validating user behavior, which improves test reliability and speed.
3. What is Playwright Test, and what does it include?
Playwright Test is the built-in test runner that comes with Playwright. It includes test discovery, expect assertions, fixtures, hooks, parallel execution, retries, reporters, and powerful debugging tools like Trace Viewer and Playwright Inspector. This removes the need for external runners.
4. What browsers and platforms does Playwright support?
Playwright supports Chromium, Firefox, and WebKit, enabling true cross-browser testing. It runs on Windows, macOS, and Linux, and supports both headless and headed execution. This makes it suitable for local development and CI environments.
Compared to any other framework Playwright has a lot of advantages, as it is a modern solution it's built on top of the limitation of another framework
The playwright is easy to install and learn
Playwright supports Java, Python, .NET C#, TypeScript, and JavaScript.
As Playwright doesn't use the webdriver API the execution is comparatively faster
Playwright automatically waits before making any actions where a user doesn't have to provide implicit or explicit waits
Playwright allows Network traffic control. Mocks etc.
Edge case scenarios like File upload and download can be handled easily in playwright
4. Name some disadvantages of Playwright.
Playwright doesn't support Mobile automation (They might introduce it in the future)
Playwright doesn't support legacy IE Automation
Playwright doesn’t support Safari stock browser
Some of the build tools like Teamcity is not directly support
Some of the features like Ordering, Priority, and Dependancy tests which are available in TestNG are not available in Playwright yet.
5. What are the different testing types the Playwright supports?
Playwright supports functional testing, API testing, and Component level testing.
6. What are the programming languages that the playwright supports
Playwright supports Java, Python, .NET C#, TypeScript, and JavaScript. However, the Typescript/Javascript version of Playwright is more stable and most used.
7. Briefly describe the commands that are used for Playwright installation and Execution of tests
As Playwright supports many programming languages each programming language follows its own installation process.
In this context we are using the Playwright and Javascript we need to use the following commands
Discover more
User interface
browser
Playwright
Before installation, we need to ensure that NodeJS binaries are installed in our machine and then we can use
npm init playwright@latest
The above command will install the required packages and configurations. Once done we are ready to write the test cases.
npx playwright test
The command is used for executing playwright tests. By default, the playwright executes all the tests that are available for the project.
8. What is a Configuration File in Playwright explain?
As the name indicates the configuration file is the place where we configure the execution behavior of the playwright. The configuration file is typically named playwright.config.ts(/js).
Using the configuration file we can configure headless mode, fullscreen, screenshot options, baseURL, browser options, etc.
9. What is @playwright/test package in Playwright?
The Playwright can be used with different test runners such as Mocha, Jasmine, Jest, etc. Similar way playwright has its own test runner called the playwright test. The playwright test is the default test runner for the playwright.
10. What is Page class in Playwright?
The Page class in playwright is the main class, which provides the methods to interact with the browser. It also provides a set of event handlers that helps to execute a set of actions as soon as the event triggers.
11. How to navigate to specific URLs in Playwright explain with sample tests
15. How to use assertions in Playwright? List any 5
Playwright Test uses the jest expect library for assertions.
The Playwright supports soft and hard assertions both.
Discover more
Browser
debugging
Debug
There are many assertions which expect library provides some of them are
expect(value1).toBe(value2): This helps to compare two values. Like equals of two strings etc.
expect(<Boolean_value1).toBeTruthy(): Assert two boolean values to be true.
expect(locator).toBeVisible(): Ensured specified locator is Visible on DOM
expect(locator).toContainText(expected_text): Ensures the specific DOM element contains the given text
expect(locator).toHaveClass(expected_class): Ensures the locator has specified css class
expect(locator).toHaveCount(count): Ensures the given locator count in dom should be equal to "count"
expect(page).toHaveTitle(title): Verifies the page title is the same as expected
16. What are soft assertions in Playwright?
By default when the assertions fail the test terminates, but if we use the soft assertions do not terminate the execution, but the test will be marked as failed at the end.
19. What are command line options in the Playwright? Explain 5 helpful options
The configuration file contains the same set of run time configurations, the command line options also provide the run time configurations. When the same option is used in both places the command line options take priority.
20. Some of the Important command line options
Run all the tests
npx playwright test
Run a single test file
npx playwright test tests/todo-single.spec.ts
Run multiple tests
npx playwright test tests/todo-page/ tests/landing-page/
Run tests in headed mode
npx playwright test --headed
Run tests on Specific browser
npx playwright test --browser "chromium"
Retry failed test
npx playwright test --retries 2
21. What is headed and headless mode in Playwright
The headed mode browser is just like any other browser. For example, if you open a chrome browser opens you can see it visually and perform the action on it.
The headless browser execution happens in the background, the actions and browsers are cannot be seen. The headless browser execution is faster than the headed mode.
22. Does Playwright support HTML reporters? How to Generate HTML reports in Playwright?
Playwright supports default HTML reporter. You can generate the HTML reporters using the below command.
npx playwright test --reporter=html
23. What are timeouts in Playwright? What are the different types of Timeouts available in Playwright?
Timeout ensures that before marking test execution as a failure the amount of time the Playwright needs to wait.
In Playwright timeouts can be set at different levels
Discover more
framework
Software Testing
Programming language
Test timeout: This is applicable for test and fixture execution time.
Expect timeout: Timeout for assertions
Action timeout: Timeout for each action
Navigation timeout: Timeout application for Navigation actions such as page.goto() etc.
Global timeout: Global Timeout for the whole test run
beforeAll/afterAll timeout: Timeout applicable for beforeAll/afterAll hooks
Fixture timeout: This timeout is set to individual fixtures.
24. How to navigate forward and backward in Playwright?
The playwright provides specific commands to navigate backward and forward.
page.goForward() command can be used to navigate forward from the browser history
page.goBack() command can be used to navigate backward from the browser history
25. How to perform actions using the Playwright?
The Page class provides different locator strategies. First, you need to find the element using locators and then perform actions.
For example, if you need to perform a click action on a button you can do it as shown below
await page.locator('#myButton').click();
26. Does playwright support the safari browser if so can we execute the test on safari?
Unlike selenium, Playwright doesn't support the Native safari browser. The Playwright supports the open-source version of Safari which is a Webkit browser.
You can execute the tests on the Safari Webkit browser using the configurations in the config file below:
const config = {
use: {
channel: 'chrome',
},
};
By specifying in the command line parameter
npx playwright test --browser "webkit"
27. How to wait for a specific element in Playwright?
The playwright has an auto-waiting mechanism that reduces the usage of explicit waits in the test. However, in some scenarios, we might need to wait for specific elements in that case we can use the .waitFor()
Example:
const someElement = page.locator('#myElement);
await someElement.waitFor();
By default waitFor() waits for the element to be visible, however, the behavior can be changed to waitFor attached, detached, hidden
Browser context provides a way to operate multiple independent browser sessions. The browser class provides newContext() method which helps to create a new browser context.
Example:
const contxt = browser.newContext()
29. How to open multiple windows in Playwright?
The playwright provides a way to open multiple windows. In Playwright each window is called Pages.
You can create multiple pages like below
const pageOne = await context.newPage();
const pageTwo = await context.newPage();
30. How to handle iFrame in PLaywright?
The frameLocator() gets the frame on a particular page in Playwright. Using frameLocator() we can perform various actions on the iFrame
Test fixtures are used to establish an environment for each test. Some of the pre-defined fixtures are page, context, browser, browserName. The fixture is isolated for each test.
Consider you have multiple tests like below
test('basic test', async ({ page }) => {
await page.goto('https://playwright.dev/');
});
test('basic click, async ({ page }) => {
await page.locator('#logo').click();
});
Though you expect the above test to be executed one after the other, the test runs and fails. As the page fixture is isolated.
You can override the default fixtures like below.
For example, the above test can be rewritten to execute correctly
let todoPage;
test.beforeEach(async ({ page }) => {
todoPage = new TodoPage(page);
});
test('basic test', async () => {
await todoPage.goto('https://playwright.dev/');
});
test('basic click, async () => {
await todoPage.locator('#logo').click();
});
You can notice that the todoPage is shared between tests.
35. What is CodeGen in Playwright?
Playwright codeGen is similar to the selenium test recorder, the CodeGen is a tool that comes with playwright you can use it for recording the Playwright tests.
36. How to parameterize tests in Playwright?
Parameterize helps to run the same tests with multiple values, some times it is also called as data-driven testing. Playwright allows parameterization, you can use data from either csv, json or plain arrays. To implement parameterization you need to use for or foreach loop.
Example:
const fruits = ['Banana', 'Orange','Apple'];
for (const name of fruits) {
test(`testing with ${name}`, async () => {
//your code
});
}
37. Write a code to upload the file
The playwright provides a special command to upload a single file or multiple files. The command setInputFile() or setInputFiles() is used for uploading the file in Playwright.
The upload and download files are edge case scenarios, Playwright has dedicated commands for both. The download files can be performed in the playwright using the waitForEvent() in the playwright.
Example:
const [ download ] = await Promise.all([
page.waitForEvent('download'),
// Perform the action that initiates download
page.locator('button#delayed-download').click(),
]);
Once the download is complete you can get the downloaded path using the command
const downloadedPath = await download.path();
39. How to perform drag and drop in Playwright?
Drag and drop can be performed using multiple ways
Using dragTo() command
Manually specifying mouse actions
Using dragTo() function for drag and drop
You need to pass the target position locator to dragTo function
Dialog popups are native to the browser or operating systems. The dialogs need special mechanism to handle as you cannot inspect the locator for these pop-ups.
There are different types of pop ups such as alert(), confirm(), prompt()
testInfo object contains information about tests that are currently running such as duration, errors, project, status, etc. Using the testInfo object we can control the test execution.
42. What is testError Object?
The testError object in PLaywright contains information about errors thrown during the test execution such as error message, stack, and value.
43. What is global setup and tear down explain?
The global setup is one-time setup that is needed for test execution. The global setup is executed before starting any tests. For example, if you want to set up some files, and URLs you can utilize this function.
Similarly, the global teardown is a one-time teardown option provided by Playwright. The global teardown will be executed after all the tests are executed. This will be helpful to generate custom reports, sending emails, freeing up resources, etc.
The playwright provides a way to monitor browser network logs. You can capture all the request and response network logs and their status. Using the listener
The Playwright allows taking the screenshot. the page.screenshot() function is provided by Playwright to the screenshot. You can place the screenshot() command anywhere in the code to save the screenshot.
46. Does Playwright support API testing? If so how can we perform API testing?
Yes, Playwright supports API Testing. We can perform any HTTP API method calls such as GET, POST etc. using the playwright and validate the status and responses.
Visual Testing is also known as visual comparisons, where two screenshots will be compared. The first screenshot is called the reference or base image, the subsequent run will compare the recent screenshot with reference images and produce the results.
Visual comparison testing is helpful for UI testing. Using functional testing we will not be able to validate the fonts, styles, typography, alignment, etc. but using the visual comparison we can validate everything related to the application User interface.
48. Write a simple code to Test Visually
For example, if we need to compare the home page we need to write the below code in Playwright.
test('Visual test homepage', async ({ page }) => {
await page.goto('https://playwright.dev');
await expect(page).toHaveScreenshot();
});
During the first run, the playwright stores the reference image of the homepage, and the next run will be compared against the reference image.
Optionally we can pass the pixel differences if we need to ignore the minor differences in the image.
49. How to configure multiple reporters in Playwright?
The playwright allows configuring multiple reporters. The reporter option is available on the playwright.config.js, you can specify the reporter types to configure multiple reporters.
Example:
// playwright.config.js
const config = {
reporter: [
['list'],
['line'],
['json', { outputFile: 'test-results.json' }]
],
};
module.exports = config;
50. What is the serial mode in Playwright?
In some scenarios, tests may be inter dependent. The second test might need the output of the first one. Running tests parallelly in such cases will create the test cases to fail and it's like a false failure. The serial mode allows running the tests serially one after the another. If one test fails all remaining tests are skipped and can be retried as a group again.
Example:
test.describe.configure({ mode: 'serial' });
let page;
test.beforeAll(async ({ browser }) => {
page = await browser.newPage();
});
test.afterAll(async () => {
await page.close();
});
test('runs first', async () => {
await page.goto('https://playwright.dev/');
});
test('runs second', async () => {
await page.getByText('Get Started').click();
});
51. How to perform parallel execution in PLaywright?
The playwright supports parallel execution. Parallel execution can be achieved at the global level or test level in the playwright.
Parallel in test file level
The mode: 'parallel' can be passed to describe.configure() function to achieve parallelism.
We can mention the fullyParallel option in the configuration file, this makes the tests run parallelly to all tests.
//playwright.config.js
const config = {
fullyParallel: true,
};
module.exports = config;
52. How to perform mobile device emulation in Playwright?
The emulation features allow testing the application in mobile mode or tablet mode by changing the properties of the browser such as screensize, useragent, geolocation etc.
For example, if we need to test the mobile safari we can specify the option in the playwright config file like below.
const config = {
projects: [
{
name: 'Mobile Safari',
use: {
...devices['iPhone 12'],
},
},
],
};
module.exports = config;
Similarly, we can set the viewport to match the mobile or tablet screen size
const config = {
use: {
viewport: { width: 580, height: 720 },
},
};
module.exports = config;
53. Mention some of the helpful ways to debug Playwright tests.
The playwright provides multiple ways to debug.
Using the debug option in the command line.
npx playwright test --debug
Debug single test
npx playwright test example.spec.ts --debug
VSCode extension
Apart from the command line debugging option Playwright also provides the VSCode extension "Playwright Test for VSCode"
Trace on option
You can also force the Playwright to record the trace by passing the --trace on option.
Example:
npx playwright test --trace on
Pause option
page.pause() can also be used inside the test script to pause the test and do some debugging.
54. What is actionability in Playwright? Explain in detail
Playwright architecture has a special type of checks before performing any actions on elements. The checks are called actionability checks.
For example when you do click operation page.click()
It will perform many checks internally such as
Element is attached to DOM
Element is Visible
Element is Stable and animation is completed(if any)
Element is ready to receive the events
Element is enabled.
This mechanism is also called automatic waiting in the Playwright. Since the Playwright performs all the above checks by default one is no need to perform the above checks manually.
55. Mention some of the advantages of Playwright compared to Cypress
The Cypress and Playwright share a lot of similarities and Playwright overcomes a lot of limitations that cypress has
Compared to any other framework Playwright has a lot of advantages, as it is a modern solution it's built on top of the limitation of another framework
The playwright is easy to install and learn
Playwright supports Java, Python, .NET C#, TypeScript, and JavaScript.
As Playwright doesn't use the webdriver API the execution is comparatively faster
Playwright automatically waits before making any actions where a user doesn't have to provide implicit or explicit waits
Playwright allows Network traffic control. Mocks etc.
Edge case scenarios like File upload and download can be handled easily in playwright
4. Name some disadvantages of Playwright.
Playwright doesn't support Mobile automation (They might introduce it in the future)
Playwright doesn't support legacy IE Automation
Playwright doesn’t support Safari stock browser
Some of the build tools like Teamcity is not directly support
Some of the features like Ordering, Priority, and Dependancy tests which are available in TestNG are not available in Playwright yet.
5. What are the different testing types the Playwright supports?
Playwright supports functional testing, API testing, and Component level testing.
6. What are the programming languages that the playwright supports
Playwright supports Java, Python, .NET C#, TypeScript, and JavaScript. However, the Typescript/Javascript version of Playwright is more stable and most used.
7. Briefly describe the commands that are used for Playwright installation and Execution of tests
As Playwright supports many programming languages each programming language follows its own installation process.
In this context we are using the Playwright and Javascript we need to use the following commands
Discover more
User interface
browser
Playwright
Before installation, we need to ensure that NodeJS binaries are installed in our machine and then we can use
npm init playwright@latest
The above command will install the required packages and configurations. Once done we are ready to write the test cases.
npx playwright test
The command is used for executing playwright tests. By default, the playwright executes all the tests that are available for the project.
8. What is a Configuration File in Playwright explain?
As the name indicates the configuration file is the place where we configure the execution behavior of the playwright. The configuration file is typically named playwright.config.ts(/js).
Using the configuration file we can configure headless mode, fullscreen, screenshot options, baseURL, browser options, etc.
9. What is @playwright/test package in Playwright?
The Playwright can be used with different test runners such as Mocha, Jasmine, Jest, etc. Similar way playwright has its own test runner called the playwright test. The playwright test is the default test runner for the playwright.
10. What is Page class in Playwright?
The Page class in playwright is the main class, which provides the methods to interact with the browser. It also provides a set of event handlers that helps to execute a set of actions as soon as the event triggers.
11. How to navigate to specific URLs in Playwright explain with sample tests
15. How to use assertions in Playwright? List any 5
Playwright Test uses the jest expect library for assertions.
The Playwright supports soft and hard assertions both.
Discover more
Browser
debugging
Debug
There are many assertions which expect library provides some of them are
expect(value1).toBe(value2): This helps to compare two values. Like equals of two strings etc.
expect(<Boolean_value1).toBeTruthy(): Assert two boolean values to be true.
expect(locator).toBeVisible(): Ensured specified locator is Visible on DOM
expect(locator).toContainText(expected_text): Ensures the specific DOM element contains the given text
expect(locator).toHaveClass(expected_class): Ensures the locator has specified css class
expect(locator).toHaveCount(count): Ensures the given locator count in dom should be equal to "count"
expect(page).toHaveTitle(title): Verifies the page title is the same as expected
16. What are soft assertions in Playwright?
By default when the assertions fail the test terminates, but if we use the soft assertions do not terminate the execution, but the test will be marked as failed at the end.
19. What are command line options in the Playwright? Explain 5 helpful options
The configuration file contains the same set of run time configurations, the command line options also provide the run time configurations. When the same option is used in both places the command line options take priority.
20. Some of the Important command line options
Run all the tests
npx playwright test
Run a single test file
npx playwright test tests/todo-single.spec.ts
Run multiple tests
npx playwright test tests/todo-page/ tests/landing-page/
Run tests in headed mode
npx playwright test --headed
Run tests on Specific browser
npx playwright test --browser "chromium"
Retry failed test
npx playwright test --retries 2
21. What is headed and headless mode in Playwright
The headed mode browser is just like any other browser. For example, if you open a chrome browser opens you can see it visually and perform the action on it.
The headless browser execution happens in the background, the actions and browsers are cannot be seen. The headless browser execution is faster than the headed mode.
22. Does Playwright support HTML reporters? How to Generate HTML reports in Playwright?
Playwright supports default HTML reporter. You can generate the HTML reporters using the below command.
npx playwright test --reporter=html
23. What are timeouts in Playwright? What are the different types of Timeouts available in Playwright?
Timeout ensures that before marking test execution as a failure the amount of time the Playwright needs to wait.
In Playwright timeouts can be set at different levels
Discover more
framework
Software Testing
Programming language
Test timeout: This is applicable for test and fixture execution time.
Expect timeout: Timeout for assertions
Action timeout: Timeout for each action
Navigation timeout: Timeout application for Navigation actions such as page.goto() etc.
Global timeout: Global Timeout for the whole test run
beforeAll/afterAll timeout: Timeout applicable for beforeAll/afterAll hooks
Fixture timeout: This timeout is set to individual fixtures.
24. How to navigate forward and backward in Playwright?
The playwright provides specific commands to navigate backward and forward.
page.goForward() command can be used to navigate forward from the browser history
page.goBack() command can be used to navigate backward from the browser history
25. How to perform actions using the Playwright?
The Page class provides different locator strategies. First, you need to find the element using locators and then perform actions.
For example, if you need to perform a click action on a button you can do it as shown below
await page.locator('#myButton').click();
26. Does playwright support the safari browser if so can we execute the test on safari?
Unlike selenium, Playwright doesn't support the Native safari browser. The Playwright supports the open-source version of Safari which is a Webkit browser.
You can execute the tests on the Safari Webkit browser using the configurations in the config file below:
const config = {
use: {
channel: 'chrome',
},
};
By specifying in the command line parameter
npx playwright test --browser "webkit"
27. How to wait for a specific element in Playwright?
The playwright has an auto-waiting mechanism that reduces the usage of explicit waits in the test. However, in some scenarios, we might need to wait for specific elements in that case we can use the .waitFor()
Example:
const someElement = page.locator('#myElement);
await someElement.waitFor();
By default waitFor() waits for the element to be visible, however, the behavior can be changed to waitFor attached, detached, hidden
Browser context provides a way to operate multiple independent browser sessions. The browser class provides newContext() method which helps to create a new browser context.
Example:
const contxt = browser.newContext()
29. How to open multiple windows in Playwright?
The playwright provides a way to open multiple windows. In Playwright each window is called Pages.
You can create multiple pages like below
const pageOne = await context.newPage();
const pageTwo = await context.newPage();
30. How to handle iFrame in PLaywright?
The frameLocator() gets the frame on a particular page in Playwright. Using frameLocator() we can perform various actions on the iFrame
Test fixtures are used to establish an environment for each test. Some of the pre-defined fixtures are page, context, browser, browserName. The fixture is isolated for each test.
Consider you have multiple tests like below
test('basic test', async ({ page }) => {
await page.goto('https://playwright.dev/');
});
test('basic click, async ({ page }) => {
await page.locator('#logo').click();
});
Though you expect the above test to be executed one after the other, the test runs and fails. As the page fixture is isolated.
You can override the default fixtures like below.
For example, the above test can be rewritten to execute correctly
let todoPage;
test.beforeEach(async ({ page }) => {
todoPage = new TodoPage(page);
});
test('basic test', async () => {
await todoPage.goto('https://playwright.dev/');
});
test('basic click, async () => {
await todoPage.locator('#logo').click();
});
You can notice that the todoPage is shared between tests.
35. What is CodeGen in Playwright?
Playwright codeGen is similar to the selenium test recorder, the CodeGen is a tool that comes with playwright you can use it for recording the Playwright tests.
36. How to parameterize tests in Playwright?
Parameterize helps to run the same tests with multiple values, some times it is also called as data-driven testing. Playwright allows parameterization, you can use data from either csv, json or plain arrays. To implement parameterization you need to use for or foreach loop.
Example:
const fruits = ['Banana', 'Orange','Apple'];
for (const name of fruits) {
test(`testing with ${name}`, async () => {
//your code
});
}
37. Write a code to upload the file
The playwright provides a special command to upload a single file or multiple files. The command setInputFile() or setInputFiles() is used for uploading the file in Playwright.
The upload and download files are edge case scenarios, Playwright has dedicated commands for both. The download files can be performed in the playwright using the waitForEvent() in the playwright.
Example:
const [ download ] = await Promise.all([
page.waitForEvent('download'),
// Perform the action that initiates download
page.locator('button#delayed-download').click(),
]);
Once the download is complete you can get the downloaded path using the command
const downloadedPath = await download.path();
39. How to perform drag and drop in Playwright?
Drag and drop can be performed using multiple ways
Using dragTo() command
Manually specifying mouse actions
Using dragTo() function for drag and drop
You need to pass the target position locator to dragTo function
Dialog popups are native to the browser or operating systems. The dialogs need special mechanism to handle as you cannot inspect the locator for these pop-ups.
There are different types of pop ups such as alert(), confirm(), prompt()
testInfo object contains information about tests that are currently running such as duration, errors, project, status, etc. Using the testInfo object we can control the test execution.
42. What is testError Object?
The testError object in PLaywright contains information about errors thrown during the test execution such as error message, stack, and value.
43. What is global setup and tear down explain?
The global setup is one-time setup that is needed for test execution. The global setup is executed before starting any tests. For example, if you want to set up some files, and URLs you can utilize this function.
Similarly, the global teardown is a one-time teardown option provided by Playwright. The global teardown will be executed after all the tests are executed. This will be helpful to generate custom reports, sending emails, freeing up resources, etc.
The playwright provides a way to monitor browser network logs. You can capture all the request and response network logs and their status. Using the listener
The Playwright allows taking the screenshot. the page.screenshot() function is provided by Playwright to the screenshot. You can place the screenshot() command anywhere in the code to save the screenshot.
46. Does Playwright support API testing? If so how can we perform API testing?
Yes, Playwright supports API Testing. We can perform any HTTP API method calls such as GET, POST etc. using the playwright and validate the status and responses.
Visual Testing is also known as visual comparisons, where two screenshots will be compared. The first screenshot is called the reference or base image, the subsequent run will compare the recent screenshot with reference images and produce the results.
Visual comparison testing is helpful for UI testing. Using functional testing we will not be able to validate the fonts, styles, typography, alignment, etc. but using the visual comparison we can validate everything related to the application User interface.
48. Write a simple code to Test Visually
For example, if we need to compare the home page we need to write the below code in Playwright.
test('Visual test homepage', async ({ page }) => {
await page.goto('https://playwright.dev');
await expect(page).toHaveScreenshot();
});
During the first run, the playwright stores the reference image of the homepage, and the next run will be compared against the reference image.
Optionally we can pass the pixel differences if we need to ignore the minor differences in the image.
49. How to configure multiple reporters in Playwright?
The playwright allows configuring multiple reporters. The reporter option is available on the playwright.config.js, you can specify the reporter types to configure multiple reporters.
Example:
// playwright.config.js
const config = {
reporter: [
['list'],
['line'],
['json', { outputFile: 'test-results.json' }]
],
};
module.exports = config;
50. What is the serial mode in Playwright?
In some scenarios, tests may be inter dependent. The second test might need the output of the first one. Running tests parallelly in such cases will create the test cases to fail and it's like a false failure. The serial mode allows running the tests serially one after the another. If one test fails all remaining tests are skipped and can be retried as a group again.
Example:
test.describe.configure({ mode: 'serial' });
let page;
test.beforeAll(async ({ browser }) => {
page = await browser.newPage();
});
test.afterAll(async () => {
await page.close();
});
test('runs first', async () => {
await page.goto('https://playwright.dev/');
});
test('runs second', async () => {
await page.getByText('Get Started').click();
});
51. How to perform parallel execution in PLaywright?
The playwright supports parallel execution. Parallel execution can be achieved at the global level or test level in the playwright.
Parallel in test file level
The mode: 'parallel' can be passed to describe.configure() function to achieve parallelism.
We can mention the fullyParallel option in the configuration file, this makes the tests run parallelly to all tests.
//playwright.config.js
const config = {
fullyParallel: true,
};
module.exports = config;
52. How to perform mobile device emulation in Playwright?
The emulation features allow testing the application in mobile mode or tablet mode by changing the properties of the browser such as screensize, useragent, geolocation etc.
For example, if we need to test the mobile safari we can specify the option in the playwright config file like below.
const config = {
projects: [
{
name: 'Mobile Safari',
use: {
...devices['iPhone 12'],
},
},
],
};
module.exports = config;
Similarly, we can set the viewport to match the mobile or tablet screen size
const config = {
use: {
viewport: { width: 580, height: 720 },
},
};
module.exports = config;
53. Mention some of the helpful ways to debug Playwright tests.
The playwright provides multiple ways to debug.
Using the debug option in the command line.
npx playwright test --debug
Debug single test
npx playwright test example.spec.ts --debug
VSCode extension
Apart from the command line debugging option Playwright also provides the VSCode extension "Playwright Test for VSCode"
Trace on option
You can also force the Playwright to record the trace by passing the --trace on option.
Example:
npx playwright test --trace on
Pause option
page.pause() can also be used inside the test script to pause the test and do some debugging.
54. What is actionability in Playwright? Explain in detail
Playwright architecture has a special type of checks before performing any actions on elements. The checks are called actionability checks.
For example when you do click operation page.click()
It will perform many checks internally such as
Element is attached to DOM
Element is Visible
Element is Stable and animation is completed(if any)
Element is ready to receive the events
Element is enabled.
This mechanism is also called automatic waiting in the Playwright. Since the Playwright performs all the above checks by default one is no need to perform the above checks manually.
55. Mention some of the advantages of Playwright compared to Cypress
The Cypress and Playwright share a lot of similarities and Playwright overcomes a lot of limitations that cypress has
A playwright can test the cross-domain URLs whereas Cypress doesn't support
Playwright supports Safari Webkit browser Cypress doesn't support Safari
Playwright supports multiple languages such as Java, Javascript, Python, and C#, the Cypress supports only Javascript/Typescript
Best Practices in Playwright Automation
Playwright is a powerful end-to-end testing framework for modern web apps, offering cross-browser support for Chrome, Firefox, and WebKit. It’s favoured for its speed, reliability, and ability to handle both web and mobile testing scenarios. However, like any tool, the key to maximising its effectiveness lies in following best practices. This guide will dive into various areas of best practices, ranging from test structure to performance optimization, helping you get the most out of the Playwright Automation Testing tool.
1. Test Design and Structure
A well-organised test suite is crucial for maintaining scalability and readability as your project grows.
Use Page Object Model (POM): The Page Object Model is a design pattern that encourages separating test code from page-specific code. This promotes reusability and reduces the maintenance effort when page layouts change. In POM, each page of your web app is represented by a class, with methods corresponding to different interactions. This abstraction layer ensures that tests remain clear and concise.
Write Independent Tests: Each test should be self-contained and not depend on the outcome of other tests. If one test fails, the others should still execute without any issues.
Use Tags or Descriptions: For better test reporting and organising, it’s beneficial to add descriptive titles or tags for your tests. This will help group related tests and make it easier to run specific ones based on functionality, priority, or category like type of testing.
Follow DRY (Don’t Repeat Yourself): Avoid duplication of code. Common functionality such as navigation, authentication, or setup steps should be refactored into helper functions or methods in your page objects so that code duplications can be avoided.
2. Handling Asynchronous Code
Playwright heavily relies on promises and asynchronous code due to the nature of browser automation. Handling async code effectively ensures that your tests are reliable.
Use await Consistently: In Playwright, most interactions with the page, such as clicking, filling inputs, or navigating. Make sure to consistently use await to avoid timing issues. Forgetting to do so might lead to tests failing intermittently or unexpectedly.
Set Timeouts Smartly: Playwright has generous default timeouts, but there are scenarios where you might need to adjust them. For instance, if you expect a specific action to take longer, you can customise the timeout for that interaction.
Headless Mode: While developing or debugging, running tests in headful mode (with the browser UI visible) can be helpful. However, for faster execution, especially in CI/CD pipelines, headless mode (default in Playwright) is preferred since it consumes fewer resources which allows fast execution.
4. Assertions and Test Validation
Clear, meaningful assertions help in verifying that your test outcomes match expectations.
Use Playwright’s Built-in Assertions: Playwright provides built-in assertions like toHaveText, toBeVisible, and toHaveAttribute, which are optimized for web interactions and will automatically wait for conditions to be met before failing the test.
Avoid Hard Waits: Hard waits like await page.waitForTimeout(5000) should be avoided because they unnecessarily slow down tests and make them less reliable. Instead, use event-based waiting mechanisms like page.waitForSelector or page.waitForResponse to ensure your test proceeds as soon as the condition is met.
5. Test Data Management
Managing test data effectively is crucial for ensuring that your tests remain predictable and reliable.
Write Cross-browser Compatible Tests: Ensure that your tests are not dependent on browser-specific behavior. Avoid using features or APIs that are exclusive to one browser unless you’re targeting a specific browser.
Run Tests Across Devices: Playwright allows testing on mobile devices and desktop devices by providing device emulations (i.e., iPhone, Galaxy, etc.). This is useful for ensuring responsive web design and functionality across different screen sizes.
Skip Unnecessary Steps: For non-essential parts of your test, like waiting for animations or ads to load, consider skipping them by controlling network requests or intercepting them to prevent delays.
6. CI/CD Integration
Automating tests in a CI/CD pipeline ensures fast executions and quality control.
7. Debugging and Troubleshooting
Debugging test failures is a vital part of maintaining a healthy test suite.
8.Test Case Naming Conventions
Test case names should be descriptive and indicate the purpose of the test clearly. A good naming convention is crucial when tests fail since it helps identify the test’s intent. For example, instead of naming a test test1, opt for something like LoginToAmazonWithRightCred.
10. How can you intercept network requests in Playwright?
Ans. You can intercept and modify network requests using the route method:
await page.route('**/*', route => { console.log(route.request().url()); // Log request URLs route.continue(); // Allow the request to continue });
You can also modify or block specific requests:
awaitpage.route('**/api/*', route => { if (route.request().url().includes('/api/private')) { route.abort(); // Block private API requests } else { route.continue(); } });