Playwright Interview Question
Playwright Interview Question
Windows
Mac OS
Linux
Chromium
WebKit (Mac)
Firefox
JavaScript
Typescript
JAVA
C#
Python
await page.goto('https://letzdotesting’.com);
await page.locator('your-selector').innerText();
await page.locator('your-selector').clear();
await page.locator('your-selector’).click();
await page.locator('your-selector').isVisible();
await page.locator('your-selector').isChecked();
await page.locator('your-selector').isEnabled();
await page.locator('your-selector').isDisabled();
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?
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
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()
await page.goto('https://example.com');
await page.reload(); // Refresh your current page
await page.locator('your-selector').contextMenu();
await page.locator('your-selector').dblclick();
await page.locator('your-selector').scrollIntoView();
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");
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.
await page.waitForSelector('.my-element');
await page.waitForNavigation();
await page.waitForXPath('//div[@class="my-element"]');
page.waitForTimeOut(2000)
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:
...devices['iPhone 11'],
});
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.
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
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.
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.
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:
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
};
Here are the steps you can follow to handle browser automation in Playwright:
npm i -D @Playwright/test
Install browsers on which you want to run a test with the command given below:
Write a tiny script for automation testing. Here is an example of running the Playwright test in
Chrome browser.
(async () => {
// Navigate to a URL
await page.goto('https://www.lambdatest.com/');
await browser.close();
})();
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.
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://www.lambdatest.com');
await browser.close();
})();
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:
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 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.
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";
=> {
await page.goto("https://www.lambdatest.com/selenium-
playground/bootstrap-date-picker-demo");
let date = "1994-12-04"
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) {
condensed']//th[@class='datepicker-switch'])[1]");
condensed']//th[@class='prev'])[1]");
condensed']//th[@class='next'])[1]");
// let dateToSelect: string = "May 2019";
YYYY").isBefore();
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.
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.
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:
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: '/',
httpOnly: true,
secure: true
});
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: '/',
httpOnly: true,
secure: true
});
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');
});
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:
XPath Selector:
ID Selector:
Text Selector:
('a[href="https://www.lambdatest.com/"]');
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.
getComputedStyle(el).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');
parseFloat(getComputedStyle(el).fontSize));
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.
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.
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();
};
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.
Official Documentation
Release notes
Community forum
GitHub repository
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
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.
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;
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 }) => { /* ... */ });