0% found this document useful (0 votes)
827 views52 pages

Playwright Interview Question

Uploaded by

Binod Yadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
827 views52 pages

Playwright Interview Question

Uploaded by

Binod Yadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 52

1. What is Playwright?

 Playwright is an open-source automation framework for end-end testing, browser


automation and browser manipulation
 Supports cross-browser testing and parallel testing
 Supports scripting in multiple programming languages
 Supports platform compatibility
 Supports network interception
 Supports Multi-page and Multi-Context
 Supports headless and headful mode

2. What are the platforms supported by Playwright?

 Windows
 Mac OS
 Linux

3. What are the different browsers supported by Playwright?

 Chromium
 WebKit (Mac)
 Firefox

4. What are the different programming languages supported by Playwright?

 JavaScript
 Typescript
 JAVA
 C#
 Python

5. What are the different types of locators in Playwright?

Locators are used to identify web elements within the webpage.


 ID
 Name
 ClassName
 CSS Selector
 XPath
 Text Content
 TagName
 AltText
 Attribute
 Label
 Role
 Title
 TestID

6. What is the command used to launch a browser?

const browser = await chromium.launch(); // launch Chrome browser

const browser = await webkit.launch(); // launch Safari browser

const browser = await firefox.launch(); // launch Firefox browser

7. What is the command to launch a URL?

await page.goto('https://letzdotesting’.com);

8. What is the command used to get the current page URL?

const currentUrl= await page.url();

9. What is the command to get the webpage title?

const title = await page.title();

10. What is the command to type values in a textbox?

await page.locator('input[type="text"]').fill('Hello, Letzdotesting!’);


await page.locator('input[type="text”]’).type(‘Hello, Letzdotesting!’);

11. What is the command to get the text values ?

await page.locator('your-selector').innerText();

12. What is the command to clear values in a textbox?

await page.locator('your-selector').clear();

13. What is the command to click a control?

await page.locator('your-selector’).click();

14. What is the command to click on a hyperlink?

const hyperlink = page.locator('a').click();

15. What is the command to find if an element is displayed on a screen?

await page.locator('your-selector').isVisible();

16. What is the command to verify if a checkbox/radio is selected?

await page.locator('your-selector').isChecked();

17. What is the command to verify if a button is enabled?

await page.locator('your-selector').isEnabled();

18. What is the command to verify if a button is disabled?

await page.locator('your-selector').isDisabled();

19. What is the command to verify if a textbox is editable?

await page.locator('your-selector’).isEditable();
20. What is the command to take a screenshot of an element?

await page.locator('your-selector’).screenshot();

21. What are the different commands used to select a dropdown list?

await page.selectOption('select#dropdownId', { label: 'OptionText' }); //SelectByVisisbleText

await page.selectOption('select#dropdownId', { index: 2 }); //SelectByIndex

await page.selectOption('select#dropdownId', 'OptionValue'); //SelectByValue

22. What are the different commands used to deselect a dropdown list?

Playwright doesn’t have a built-in method for deselecting options from a dropdown like
the deselect method in Selenium. However, you can achieve a similar effect by
reselecting the desired options

23. Name any 4 commonly used Assertions in Playwright?

Playwright, being a tool primarily designed for browser automation, does not inherently
include assertion methods like traditional testing frameworks. Assertions are usually
part of the testing frameworks that you use in combination with Playwright.

When using Playwright with a testing framework such as Jest, Mocha, or Jasmine, you
typically use the assertion methods provided by those frameworks. Here are some
commonly used assertion methods from Jest framework:

 expect(value).toBe(expected)
 expect(value).toEqual(expected)
 expect(value).toBeTruthy()
 expect(value).toBeFalsy()

24. What are the different navigation commands?

await page.goto('https://example.com');
await page.reload(); // Refresh your current page

await page.goBack(); // Takes one page backward based on browser's history

await page.goForward(); // Takes one page forward based on browser's history

25. What is the command to right click?

await page.locator('your-selector').contextMenu();

await page.locator('your-selector').click({ button: 'right' });

26. What is the command to double-click?

await page.locator('your-selector').dblclick();

27. What is the command used to scroll down to a web element?

await page.locator('your-selector').scrollIntoView();

28. What is the command to drag and drop?

const sourceElement = await page.locator('your-source-selector');

const targetElement = await page.locator('your-target-selector');

await sourceElement.dragAndDrop(targetElement);
29. What is the command used to get the attribute values of an element?

await page.locator('your-selector').getAttribute("value");

30. What is the difference between locator() and locateAll()?

 locator() – Finds the first matching element in the DOM & returns a single
element.
 locateAll() – Finds all the matching elements in the DOM & returns a list of
elements.

31. Write code to close the entire browser.

browser.close() - Used to close entire browser

32. Write code to close an individual page or tab

page.close() - Used to close individual page

33. What are the different types of waits available in Playwright?

await page.waitForSelector('.my-element');

await page.waitForNavigation();

await page.waitForXPath('//div[@class="my-element"]');

page.waitForTimeOut(2000)

await page.waitForEvent('response', response => response.status() === 200);


await page.waitForRequest('https://example.com/api/data');

34. How to handle iFrames?

const iframe = page.frame({ name: 'myIframe' }); // Based on name

await page.waitForSelector('iframe[name="myIframe"]'); // Based on WebElement

await page.bringToFront(); // Switch back to the main context

35. Name any three testing frameworks that can be integrated with Playwright?

 Jest
 Mocha
 Jasmine

36. How do you handle touch events in mobile emulation with Playwright?

page.touchscreen.tap()

37. What software and tools do you need to run Playwright in Typescript?

 Node.js
 npm (Node Package Manager)
 Playwright (npm install playwright)
 Typescript (npm install -g typescript)
 Visual Studio Code

38. Name any advanced framework design that can be used with Playwright?

 Cucumber (BDD)
 Page Object Model
 Data-driven testing
 Parallel testing
 Cross-browser testing
 Configuration Properties
 Utilities
 Tests
 Logging
 Reporting

39. Name any 5 Exceptions that you got while working with Playwright

 NavigationException
 TimeOutException
 BrowserContextException
 ElementHandleException
 SelectorException:

40. Can you provide an example of how to set up mobile emulation in a


Playwright test script?

const { devices } = require('playwright');

const context = await browser.newContext({

...devices['iPhone 11'],

});

1. What is the Playwright framework, and


what are its key features?
Playwright is a Node.js library developed by Microsoft that automates Chromium, Firefox,
and WebKit with a single API. Developers writing JavaScript code can use these APIs to
build new browser pages, navigate to URLs, and interact with page elements. Furthermore,
because Microsoft Edge is based on the open-source Chromium web framework, Playwright
may automate Microsoft Edge.
Some key features make Playwright different:

 Cross-browser development on Chromium, WebKit, and Firefox is supported, including Chrome,


Edge, Firefox, Opera, and Safari. Cross-platform execution is possible on Windows, Linux, and
macOS.

 Cross-language testing, including JavaScript, TypeScript, Python, Java, and .NET, allows you to
choose the best environment for you while covering all regions and formats.

 Keep track of logs and videos effortlessly using auto-wait, clever assertions that retry until an
element is located, and test data tracing.

 Playwright frameworks take full-page screenshots of the webpage, which makes visual testing
easier.

 It is built with current architecture and no constraints, allowing you to interact with multi-page,
multi-tab websites like a genuine user, and effortlessly handles frames and browser events.

 Because the Playwright framework is built on the architecture of modern browsers, it does not
have the constraints of an in-process test runner.
Note : Accelerate Playwright Automation testing with LambdaTest.

2. How does Playwright differ from other


testing frameworks?
Released in 2020, Playwright is gaining popularity every day. The Playwright is registering
1.3 million downloads every week on NPM as of April 2023. The reason is it has many
advantages over other frameworks. It enables you to test complex web applications across
several browsers. It gives superior test coverage and reliable findings. Additionally, there
are several benefits to automating your web testing. Such as:

 It includes capabilities for step-by-step debugging, exploring selectors, and recording new tests.
It is accessible as a VS Code addon.

 To examine test execution results in a browser, Playwright creates an HTML report. Visual
discrepancies and test artifacts like screenshots, traces, error logs, and video recordings are
included.

 Playwright installation just takes a few minutes to be configured. However, the installation
procedure may vary depending on the programming language you use with Playwright to
perform the tests.

 Playwright offers a high-level API that frees you from dealing with low-level browser interactions
so that you may design tests that are easier to comprehend and manage.

 Playwright includes built-in parallelism support, allowing you to run tests simultaneously across
many browsers or computers, which can help you save time and expedite your test runs.

 You can test your application on various mobile devices and screen sizes because of Playwright's
ability to emulate mobile devices.
3. What programming languages does
Playwright support?
Here is the list of programming languages Playwright supports:

 JavaScript/Node.js

 TypeScript

 Python

 C#

 Java

4. Is there any Webdriver dependency in


Playwright?
No, Playwright is not dependent on WebDriver. Playwright communicates with the browser
via a different protocol than WebDriver-based automation tools. It uses the DevTools
protocol, a more advanced and effective method of controlling the browser.
5. Can you describe Playwright's architecture?
To understand Playwright architecture better, we will compare it with the Selenium
structure. Selenium sends each command as a separate HTTP request, and it receives JSON
replies in return. Then, a separate HTTP request is issued for each interaction, such as
opening a browser window, selecting an object, or typing text into a text field.
As a result, we must wait longer for responses, and the likelihood of mistakes rises.

Playwright uses a single WebSocket connection to communicate with all drivers, which is
kept open until testing is complete, instead of having separate connections for each driver.
This lowers the number of potential failure sites by enabling rapid command transmission
via a single link.

6. Can I perform tests for Playwright using


Jasmine?
Yes, we can use Jasmine as the test runner for Playwright since Jest and Jasmine have
nearly identical syntax.

7. What is the difference between Playwright


and Puppeteer?
Playwright is the first release as a fork of Puppeteer. Puppeteer is a node library that uses
JavaScript to automate Chromium-based browsers. Even though Playwright started as one
fork of Puppeteer, there are many key differences.

Cross-browser interoperability is Playwright's key differentiator. It can power Firefox,


Chromium, and WebKit (the Safari browser engine). Along with this, Playwright was able
to enhance ergonomics in ways that might damage Puppeteer by beginning a new library.

Playwright's page.click, for instance, waits for an element to be visible. Puppeteer still has
room for improvement, although Playwright is sometimes a better option.

The Playwright automation platform's more robust browser context features, which let you
simulate many devices with a single instance, are the final notable difference. Multiple sites
may be nested within a single browser context, and each context is independent of the others
in terms of cookies and local storage.

Contrarily, browser automation can be started quickly using Puppeteer testing. This is
partially attributable to its simplicity of usage, as it manages Chrome using the unusual
DevTools interface, makes it simple to intercept network requests, and offers more
capabilities than Selenium.

Playwright Automation interview


questions

8. How can I install Playwright with NodeJS?


You can install Playwright easily from NodeJS. Here are the steps to follow:

 Launch a command prompt or terminal window.

 Go to the project directory where Playwright should be installed.

 To install the Playwright package, do the following command:

npm install Playwright

The most recent version of Playwright and its dependencies will be installed in your project
directory.

 When the installation is finished, import Playwright into your JavaScript code:

const { chromium } = require('Playwright');


This imports the Playwright library's Chrome browser object, which you can use to
automate browsing activities and tests.

9. Can I run tests parallelly in Playwright?


Yes, Playwright enables parallel test execution, enabling you to speed up your test suite by
running several tests concurrently. A test runner that supports parallel execution, such as
Jest or Mocha, can be used to execute tests in parallel.

For instance, If you are using Jest, then --runInBand option allows you to run tests
concurrently. The following code must be added to your jest.config.js file to activate this
option:
module.exports = {
// ...
testRunner: "jest-circus/runner",
maxConcurrency: 5, // set the maximum number of parallel tests
};

10. How does Playwright handle browser


automation and testing?
Through a single API, the Playwright library offers cross-browser automation. Chromium,
Firefox, and WebKit can all be automated using a single API, thanks to the Playwright
Node.js module. Playwright makes cross-browser online automation that is evergreen,
competent, dependable, and quickly possible.

Here are the steps you can follow to handle browser automation in Playwright:

 Install the Playwright test to perform a test on your website:

npm i -D @Playwright/test
 Install browsers on which you want to run a test with the command given below:

npx Playwright install

 Write a tiny script for automation testing. Here is an example of running the Playwright test in
Chrome browser.

const { chromium } = require('Playwright');

(async () => {

// Launch a Chrome browser instance

const browser = await chromium.launch();

// Create a new page

const page = await browser.newPage();

// Navigate to a URL

await page.goto('https://www.lambdatest.com/');

// Get the page title and log it to the console

const title = await page.title();


console.log('The page title is: ${title}');

// Close the browser

await browser.close();

})();

Also Read: A list of 70 Cucumber Interview Questions and Answers

11. Can you explain how Playwright's page


object model works?
A design technique called page object modeling enables us to model a group of objects to a
certain page type. Despite its name, a page is only sometimes what it appears to be; it could
be a part of the website. Here is how Page object model in Playwright works:

 Define page object classes: Create classes that contain methods that correspond to the many
interactions a user might have with the page, such as clicking buttons, typing text, and checking
the page's status.

 Encapsulate various page elements: The various web page components that your methods
interact with can be contained within the page object class.

 Create the page object: To instantiate the object, create a new instance of the page object class
in your test code. This grants you access to the page object class's methods.

 Use the Page object method for testing: Once your Page object model is generated, you can use
those classes for test automation.
12. How does Playwright handle asynchronous
operations?
To handle asynchronous actions and run the test phases sequentially, Playwright employs
the async/await keywords.

Playwright's methods and functions return promises that resolve after the process is finished
when you interact with a web page. For instance, when an element is clicked, the click
method provides a promise that resolves. Before performing the next operation, you can use
the await keyword to wait for the promise to resolve.

Here is a code snippet for better understanding:


const { chromium } = require('Playwright');

(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://www.lambdatest.com');

// Wait for the element to be visible before clicking it


const button = await page.waitForSelector('#my-button');
await button.click();

// Wait for an animation to finish before taking a screenshot


await page.waitForTimeout(1000); // Wait for 1 second
await page.screenshot({ path: 'lambdatest.png' });

await browser.close();
})();

13. How does Playwright integrate with


Continuous Integration (CI) tools?
When code updates are posted to your repository, Playwright works seamlessly
with Continuous Integration (CI) tools like Jenkins, Travis CI , CircleCI, and others so that
your tests run automatically. Here is the way you can integrate Playwright with CI tools:

 Verify that a browser can be executed on the CI agent. The Linux agent's Playwright Docker
image Utilizes command-line tools to install your dependencies.

 Examine the documentation for the tools or frameworks you intend to integrate; many of these
include thorough instructions on how to do so with the Playwright framework.

 Utilize the Playwright automation framework's most recent version. The framework has been
updated to make it easier to integrate with other systems.

 Verify that the two frameworks' necessary dependencies are installed and configured.
14. What are some common challenges you've
faced when using Playwright, and how did you
overcome them?
Playwright has certain drawbacks, such as not supporting Legacy Microsoft Edge or IE11,
using emulators instead of real devices, and many more. However, here are some major
common challenges with Playwrights with a possible solution:

 Setting up and keeping the test environment up to date:

Keeping the test environment up to date is one of the key Playwright difficulties. It
can involve setting up browsers, installing dependencies, and configuring the test
runner. The use of containerization solutions like Docker, which can provide a
consistent testing environment across many computers and environments, is advised
to address this difficulty.

 Playwright test debugging:

Playwright test debugging can be difficult, particularly when dealing with complex
situations or intermittent failures. Using debugging tools, such as the Playwright
CLI's debug command, which enables you to pause test execution and investigate the
current state of the page and the test code, is one way to get around this problem.

 Managing asynchronous activity:

Asynchronous behavior is frequently included in Playwright testing, which can be


difficult to manage. It is advised to use async/awaits syntax to get around this
problem and make sure that the tests wait for the page to load and for the required
behavior to happen before moving on to the next stage.
15. How to automate date pickers in
Playwright?
Playwright offers two major methods to automate date pickers or calendars:

 Fill method

Using the fill() command to automate date pickers is a quicker and simpler process.
The fill() function only requires the date to be sent as an argument. These are the
procedures for this approach. Here is the code snippet as an example:
import { test } from "@Playwright/test";

test("Calendar demo using fill function", async ({ page })

=> {

await page.goto("https://www.lambdatest.com/selenium-

playground/bootstrap-date-picker-demo");
let date = "1994-12-04"

await page.fill("id=birthday", date);

await page.waitForTimeout(3000)

})

 Moment method

An open-source and cost-free JavaScript tool called Moment.js aids in solving date
and time-related problems. It is a collection of native JavaScript date objects that
makes it simple to change or show date and time in JavaScript.

This method allows you to create perfect methods to test date pickers or calendars.
Here is the code snippet for better understanding.
async function selectDate(date: number, dateToSelect:

string) {

await page.click("//input[@placeholder='Start date']")

const mmYY = page.locator("(//table[@class='table-

condensed']//th[@class='datepicker-switch'])[1]");

const prev = page.locator("(//table[@class='table-

condensed']//th[@class='prev'])[1]");

const next = page.locator("(//table[@class='table-

condensed']//th[@class='next'])[1]");
// let dateToSelect: string = "May 2019";

const thisMonth = moment(dateToSelect, "MMMM

YYYY").isBefore();

console.log("this month? " + thisMonth);

while (await mmYY.textContent() != dateToSelect) {

if (thisMonth) {

await prev.click();

} else {

await next.click();

}
16. How do you debug tests in Playwright?
Playwright offers various methods to debug tests, as mentioned below:

 VS Code debugger:

If you are using VS code extension, you can step through your tests while debugging
them, view error messages, and create breakpoints. Here are the steps you can
follow. If your test fails, VS Code will display error messages directly in the editor
that include a call log, what was anticipated, and what was received.

In VS Code, you may actively debug your test. Click on any of the locators in VS
Code after running a test with the Show Browser checkbox selected, and it will be
highlighted in the Browser window. You can see if there are several matches, thanks
to Playwright.

 Using the Playwright Command-Line Interface (CLI):

Playwright has a command-line interface (CLI) with a debug command that enables
you to halt the test execution and examine the current state of the page and the test
code. Simply add the --debug flag to your test command to activate the debug
command, and Playwright will halt test execution if it comes across a debugger
statement in your test code.

 Using the Playwright Inspector:

While your test is running, you can interact with the page and examine its state using
Playwright's interactive debugging tool, the Playwright Inspector. By adding the --
inspect flag to your test command and then navigating to the given URL in your
browser, you can start the Playwright Inspector.
17. Can you explain how Playwright handles
cookies and local storage?
During test execution, Playwright offers APIs to manage cookies and local storage in the
browser. An overview of Playwright's cookie and local storage policies is as below:

 Handling cookies in Playwright:

To obtain all of the cookies for the current page, use the cookies() function on the
page object. The setCookie() method can also be used to create a new cookie or
make changes to an existing cookie. The deleteCookie() can be used to remove a
cookie.
await page.setCookie({

name: 'myCookie',

value: 'myValue',

domain: 'example.com',

path: '/',

expires: Date.now() + 86400000, // expires in 1 day

httpOnly: true,

secure: true

});

 Handling cookies in Playwright:

To obtain all of the cookies for the current page, use the cookies() function on the
page object. The setCookie() method can also be used to create a new cookie or
make changes to an existing cookie. The deleteCookie() can be used to remove a
cookie.
await page.setCookie({

name: 'myCookie',

value: 'myValue',

domain: 'example.com',

path: '/',

expires: Date.now() + 86400000, // expires in 1 day

httpOnly: true,

secure: true

});

 Handling Local storage:

To run JavaScript code in the browser context and work with local storage, use the
evaluate() function on the page object. Here is the code snippet for it:
await page.evaluate(() => {

localStorage.setItem('myKey', 'myValue');

});

18. What are some best practices for writing


efficient and maintainable tests with
Playwright?
Here are some best practices for writing efficient test scripts with Playwright:

 Use relevant test names that are descriptive and reflect the functionality when naming your
tests. This makes comprehending the test's goal simpler, especially if you have a sizable test
suite.

 A test should be independent and atomic, meaning it should only test one object and not
depend on the results of other tests. When a test fails, it is simpler to identify and address
problems.

 Your tests will be easier to comprehend and manage if page objects are used to encapsulate
page-specific behavior. Page objects offer an abstraction layer that keeps the test code distinct
from the page's implementation specifics.

 The waitForSelector() and waitForNavigation() functions in Playwright are just two of the
mechanisms available for waiting for elements and actions to finish. Utilize these techniques to
manage timing concerns and guarantee the consistency and dependability of your testing.

 Create logical groupings for your tests depending on the features or components. Create logical
groups for your tests. It makes execution simpler to particular subsets of tests and helps
comprehend the general structure of the test suite.

 Use version control to coordinate with other team members and manage your test code. To
automate your testing procedure and guarantee that your tests are run consistently and
dependably, use continuous integration tools.
19. What is waitFor() in Playwright?
The waitFor() method in Playwright enables you to postpone the script's execution while
you wait for a particular condition to hold true. It only accepts one argument, a function that
yields a boolean value, and it iteratively executes that function until it returns true.

Here is an illustration of how to use Playwright's waitFor() function to wait for an element
to become visible:
await page.waitFor(() => {
const element = document.querySelector('#my-element');
return element && element.isVisible();
});
20. Which Selectors are used in Playwright?
To find elements on a web page, Playwright offers several selectors. Here is the list of the
most popular selectors in Playwright with an example:

 CSS Selector:

const buttons = await page.$$('button');

 XPath Selector:

const input = await page.$x('//input[@name="username"]');

 ID Selector:

const element = await page.$('#my-element');

 Text Selector:

const link = await page.$

('a[href="https://www.lambdatest.com/"]');

21. How do you get the CSS value of an


element?
Here are two methods to get the CSS value of an element:

 elementHandle.$eval() method:
Playwright's elementHandle.$eval() method allows you to obtain an element's CSS
value. This method calls a function while taking the page's context into account, then
returns the result to the caller.

Here is a code snippet for using elementHandle.$eval()


const element = await page.$('#my-element');

const backgroundColor = await element.$eval('body', el =>

getComputedStyle(el).backgroundColor);

console.log('Background color:', backgroundColor);

 elementHandle.evalute() method:

You can also run a function that returns the computed style of an element by using
the elementHandle.evaluate() method. Here's an illustration of how to use evaluate()
to determine an element's font-size:
const element = await page.$('#my-element');

const fontSize = await element.evaluate(el =>

parseFloat(getComputedStyle(el).fontSize));

console.log('Font size:', fontSize);

22. Can you walk me through setting up a new


Playwright project?
You can follow the steps below to set up a new Playwright project:

 Ensure Node.js is set up on your computer. Running node -v in your terminal or command
prompt will show you whether it is installed or not.
 In your terminal or command prompt, create a new directory for your project and go there.

 Start a new Node.js project by launching npm init and following the on-screen instructions. For
your project, this will produce a package.json file.

 Run npm install Playwright to add Playwright as a dependency.

 Install the corresponding browser driver(s) as devDependencies for the browser(s) you want to
automate with Playwright. For instance, you may install the driver by executing npm install
Playwright-chromium if you wish to automate Chromium.

 In the tests directory at the project's root, create a new file named Playwrighttest1.spec.js (or
whatever name you like). Your test code will be in this file.

23. How does Playwright ensure cross-browser


compatibility?
Web applications can be tested with Playwright on a variety of browsers, including Gecko-
based Mozilla Firefox, WebKit-based Apple Safari, and Chromium-based Google Chrome,
and the new Microsoft Edge. Playwright 1.32.3 is currently accessible on NPM.

With a foundation that prioritizes dependable and quick execution, Playwright can automate
a wide variety of scenarios across several browsers with a single API. Here is an example of
it:
const { chromium, firefox, webkit } = require('Playwright');

(async () => {
// Define the test code
const runTest = async (browserType) => {
const browser = await browserType.launch();
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://www.lambdatest.com/');
// Add test code here
await browser.close();
};

// Run the test in multiple browsers


await Promise.all([
runTest(chromium),
runTest(firefox),
runTest(webkit),
]);
})();

24. What are some common errors you might


encounter when using Playwright, and how do
you troubleshoot them?
Here is the list of errors you might encounter while using Playwright with solutions to solve
it:

 TimeoutError: When a Playwright operation takes longer to complete than the default timeout
(30 seconds), this error may appear. If the operation is stuck because of a race condition or
another problem, you can raise the timeout by giving a timeout option to the appropriate
method.

 SelectorTimeoutError: This error will appear when Playwright cannot locate an element on the
page that matches a given selector. You can solve it by verifying that the selection is accurate
and that the element is on the page when the test is run.

 NavigationError: It appears during a DNS resolution error or a server fault, which can result in a
navigation error. You can troubleshoot by verifying the URL and whether the server is up and
operating.

 ActionabilityError: This error appears when Playwright cannot carry out a specific action on an
element, like clicking a button or entering text into a text field. You can solve it by checking
whether the element is visible and in the proper condition for the operation to be performed
can help you troubleshoot.

25. How do you stay up to date with new


features and updates to the Playwright
framework?
There are various sources to be updated about Playwright automation frameworks, such as:

 Official Documentation

 Release notes

 Community forum

 Conference and events

 GitHub repository

 Twitter

1. What is Playwright?
Playwright is an open-source testing tool, which supports functional,
API, and component testing. The playwright is managed by
Microsoft.
2. What is the difference between Selenium
and Playwright?
The playwright is ready to use a Selenium Provides API/Libraries
framework one can install and you need to build the
start using. framework
Playwright shipped with in-built Selenium doesn't provide any
assertion libraries assertions, we need to
integrate using JUnit or TestNG
The playwright uses the Selenium uses the Webdriver
WebSocket connection to API/HTTP to communicate with
communicate with the browser the browser
The playwright is faster Selenium comparatively slower
compared to Selenium
The playwright doesn't support Selenium supports Safari
the safari stock browser rather it
uses the open-source, Webkit
browser to test safari
Playwright officially supports Selenium officially supports
Java, Python, .NET C#, Java, Python, C#, Ruby, Perl,
TypeScript, and JavaScript. PHP, and JavaScript

3.What are the advantages of a Playwright?


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.
 It supports both API and end-to-end testing
 Playwright supports Chromium-based browsers, Firefox,
Safari(Webkit)
 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
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
const { test, expect } = require("@playwright/test");
test.describe("navigation", () => {
test("navigation", async ({ page }) => {
await page.goto("https://playwright.dev/");
});
});
The page.goto() is used for navigating to a specific URL.
The test.describe() hook is used for grouping the set of tests
The test() contains actual tests with playwright commands.
12. What are the different types of reporters
that the playwright supports?
The playwright supports different types of reports

 Dot reporter
 Line reporter
 HTML reporter
 JSON reporter
 JUnit reporter
 Custom reporter
In addition to the above playwright also supports allure reporters
using third-party plugins.
13. What are the locators in the Playwright
list of any five
Locators help to find the elements on the page uniquely at any point
in time.
The page class provides the locator function.

 page.getByText() : Find the element that matches the given


text
 page.getByRole(): Find the element that matches the role
attribute
 page.getByLabel(): Find the element that matches the label
 page.getByTestId(): Find the element that matches the data-
testid attribute
 page.getByTitle(): Find the element that matches the title
attribute
 page.locator(<css> or <xpath>): Find the element by using
the CSS or XPath
14. What are the different types of text
selectors available in Playwright?
Text-based locators in Playwright are a unique feature, that helps to
locate the element which is having specific text
locator.(<some_text) : Matches the element that has passed text
Ex: await page.locator('text=Home menu')
:text-is(): this can be used inside the CSS selector, which will
perform the exact match before finding the elements
Ex: await page.locator('#nav-bar :text-is("Home")')
:has-text(): This is another pseudo-class, which matches the
element which contains the passed text.
Example: await page.locator(':has-text("Playwright")')
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.
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.
The Playwright provides a command
expect.soft() for soft assertions
Example:
expect.soft(page.locator('#title').toHaveText('Udemy')
17. How to negate the Matchers/Assertions in
Playwright? Or How can I verify not
conditions in Playwright?
The Negation matchers are most commonly used in Playwright.
The .not can be used in Playwright to Negate the assertions
For example, if we have to verify the a should not equal 10 then we
can use
expect(a)not.toBe(10)
The not is generic keyword can be used with any assertions to
negate the condition.
18. Does Playwright support XPath? If so how
can I use them in the test?
Yes, Playwright supports both CSS and XPath selectors.
The page.locator() function can be used for XPath.
The page.locator() automatically detects the passed value is XPATH
or CSS and returns the locator accordingly
Whenever Playwright sees the selector staring with // or .. then the
playwright assumes it is the XPath
Example:
await page.locator("//button[@id='someid']").click();
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
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
Example: await someElement.waitFor({ state: 'attached' })
28. What is browser context?
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
Example:
const button = await
page.frameLocator('#my_ifr').locator('#button_my)
31. Explain some of the click and double click
actions with its options.
click(): action is used for clicking any element on the page.
dblclick: The dblclick() is used to perform the double click on the
element.
Both of the above click takes multiple parameters for example:
force: PLaywright waits for actionability it internally checks for if the
element is ready to click. The force option helps bypass this option
locator.click({force:true});
position: Position can be used to perform the coordinates with
respect to the element.
delay: can be used for time between mouseup and mousedown
32. How to perform a right-click on
Playwright?
The playwright doesn't have a separate command for right click, in
order to right click we need to use the click action with the button
parameter
Example:
locator.click({button:right})
33. How to evaluate Javascript in Playwright?
The playwright provides page.evaluate() function, which can be
used for evaluating any javascript function.
Example:
const href = await page.evaluate(() => document.location.href);
34. What are Playwright fixtures?
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.
 Example:
 Upload single file:
await page.getByLabel('Upload file ').setInputFiles('myfile.pdf');

 Upload multiple files:


await page.getByLabel('Upload files').setInputFiles(['file1.pdf',
'file2.pdf']);

 Note: Passing empty array to setInputFiles() makes


unselect the files if you are already selected.
 Example:
await page.getByLabel('Upload file').setInputFiles([]);
38. Write a code to download the file
 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
Example:
await page.locator('#item-to-be-
dragged').dragTo(page.locator('#item-to-drop-at'));
The above dragTo() function internally does

 Hovers on the item to be dragged


 Clicks on the item to be dragged
 Move the mouse to target location
 Rleases the left mouse button
As mentioned earlier, you can use the manual method, by perfoming
all the above actions instead of dragTo() function.
Manual way to drag and drop
await page.locator('#item-to-be-dragged').hover();
await page.mouse.down();
await page.locator('#item-to-drop-at').hover();
await page.mouse.up();
40. How to handle browser popups or
dialogs?
 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()
 Handling Alert
 //Click on Ok
page.on('dialog', dialog => dialog.accept());

 Handling confirm
 //Click on Ok
page.on('dialog', dialog => dialog.accept());
//Click on Cancel
page.on('dialog', dialog => dialog.dismiss ());

 Handling Prompt
 //Type the text, RSAcademy and Accept the pop up
page.on('dialog', dialog => dialog.accept("RSAcademy"));
41. What is testInfo Object?
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.
 Example Global Set up
// global-setup.js
module.exports = async config => {
const {storageState } = config.projects[0].use;
};
// playwright.config.js
const config = {
globalSetup: require.resolve('./global-setup'),
use: {
storageState: 'state.json',
},
};
module.exports = config;

 Example Global Teardown


// global-teardown.js
module.exports = async config => {
//Some code
};
// playwright.config.js
const config = {
globalTeardown: require.resolve('./global-teardown),
use: {
storageState: 'state.json',
},
};
module.exports = config;

44. How to capture Network logs in


Playwright?
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
page.on('request', request =>
console.log('>>', request.method(), request.url()));
page.on('response', response =>
console.log('<<', response.status(), response.url()));
await page.goto('https://example.com');
45. How to capture screenshots in
PLaywright?
 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.
 Take the full page screenshot
await page.screenshot({ path: 'screenshot.png', fullPage: true });

 Take the Element level screenshot


await page.locator('.header').screenshot({ path: 'screenshot.png' });
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.
Example:
test("Get users", async ({ request, baseURL }) => {
const apiResponse = await
request.get(`${baseURL}public/v2/users/`);
expect(apiResponse.ok()).toBeTruthy();
expect(apiResponse.status()).toBe(200);
});
47. What is Visual Testing? Why do we need
it?
 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.
test('example test', async ({ page }) => {
await page.goto('https://playwright.dev');
await expect(page).toHaveScreenshot({ maxDiffPixels: 100 });
});
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.
Example:
test.describe.configure({ mode: 'parallel' });
test('runs in parallel 1', async ({ page }) => { /* ... */ });
test('runs in parallel 2', async ({ page }) => { /* ... */ });

 Parallel option in the playwright config file


 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
 The playwright supports iFrame, Cypress doesn’t
 Playwright supports multiple windows/tabs, Cypress doesn't
 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

You might also like