Top Playwright Interview Questions to Ace Your Job Hunt

Playwright is a powerful end-to-end testing framework developed by Microsoft. If you’re preparing for a Playwright interview or looking to enhance your knowledge, this comprehensive guide will help you stay updated with the latest questions and trends.

Table of Contents

Introduction to Playwright

Playwright is an open-source automation library for web testing. It allows developers to write scripts in JavaScript, TypeScript, Python, C#, and Java, making it a versatile tool for automating browser interactions. Playwright supports multiple browsers, including Chromium, Firefox, and WebKit, ensuring your web applications work seamlessly across different platforms.

Why Playwright?

  • Cross-Browser Testing: Playwright can automate browsers like Chrome, Firefox, and Safari, enabling comprehensive cross-browser testing.
  • Multi-Language Support: It supports multiple programming languages, catering to a broader range of developers.
  • Headless Mode: Playwright can run browsers in headless mode, improving the speed and efficiency of your tests.
  • Automatic Waiting: Playwright waits for elements to be actionable before performing actions, reducing flakiness in tests.

Playwright Interview Questions (Basics)

1. What is Playwright, and how does it differ from other testing frameworks?

Playwright is a web testing library that supports multiple browsers and languages. It differs from other frameworks by providing robust cross-browser support and features like automatic waiting and network interception.

2. How do you install Playwright?

You can install Playwright using npm with the command npm install playwright. For specific browsers, use npm install playwright-chromium, npm install playwright-firefox, or npm install playwright-webkit.

3. What is the difference between Selenium and Playwright?

Feature Selenium Playwright

Language Support

Java, C#, Python, Ruby, JavaScript, Kotlin

JavaScript, TypeScript, Python, C#, Java

Browser Support

Chrome, Firefox, Safari, Edge, Internet Explorer

Chromium, Firefox, WebKit (Safari)

Headless Browser Support

Yes

Yes

API Design

Larger and more complex API surface

Modern, concise, and consistent API

Auto-Wait

No built-in auto-wait; explicit waits often required.

Built-in auto-waiting for elements and assertions.

Parallel Execution

Supports parallel execution with frameworks like TestNG, JUnit

Built-in parallel execution with isolated browser contexts

Network Interception

Limited; requires additional tools/libraries

Full support for request interception and modification

4. Can you explain the concept of headless testing and its benefits in Playwright?

Headless testing refers to running browser tests without a graphical user interface (GUI). In this mode, the browser operates in the background, allowing automated tests to be executed more efficiently and quickly, as rendering the GUI is not required. This is particularly useful in continuous integration and deployment (CI/CD) pipelines where speed and resource utilization are critical.

Benefits of Headless Testing:

  1. Speed: Without the need to render a GUI, tests run faster.
  2. Resource Efficiency: Less memory and CPU usage since the graphical interface is not loaded.
  3. Automation-Friendly: Ideal for automated environments like CI/CD pipelines.
  4. Scalability: Easier to scale as headless browsers can run in parallel without consuming extensive resources.

5. What is Page Class in Playwright?

The Page class in Playwright represents a single tab or window in a browser context. It provides a high-level API to interact with the content of a web page, allowing you to perform various actions such as navigating to URLs, clicking elements, filling out forms, capturing screenshots, and executing scripts. Essentially, the Page class is your primary interface for interacting with web content in Playwright.

(i) Exact Text Match:

  • This selects elements that contain the exact text.
  • Syntax: text=”exact text”
  • Example: await page.click(‘text=”Submit”‘);

(ii) Partial Text Match:

  • This selects elements that contain the specified text as a substring.
  • Syntax: text=partial text
  • Example: await page.click(‘text=Submit’);

(iii) Case-Sensitive Exact Text Match:

  • Syntax: text=”exact text” s
  • Example: await page.click(‘text=”Submit” s’);

Playwright allows the use of regular expressions for more advanced text matching

(iv) Regular Expression Match:

  • This selects elements based on a regular expression.
  • Syntax: text=/regex/
  • Example: await page.click(‘text=/Sub.*/’);

(v) Case-Sensitive Regular Expression Match:

  • This can be achieved by using the regular expression flag i for case-insensitivity (by default, regular expressions are case-sensitive).
  • Example: await page.click(‘text=/submit/i’);

6. How to wait for a specific element in Playwright?

Playwright has an auto wait mechanism which reduces the usage of explicit waits, but in some cases we might need to wait for some specific elements. 

Playwright offers several methods to wait for specific elements:

(i) Using page.waitForSelector()

-> The waitForSelector() method waits until a specific element appears in the DOM, with options to customize its waiting conditions.

Syntax: await page.waitForSelector(selector, options);

(ii) Using page.waitForTimeout()

-> If you want to add a fixed delay (not recommended for waiting on dynamic elements), you can use waitForTimeout().

Syntax: await page.waitForTimeout(milliseconds);

(iii) Using page.waitForFunction()

-> The waitForFunction() method allows you to wait for a specific condition or expression, providing flexibility beyond element appearance.

Syntax: await page.waitForFunction(function);

Playwright Interview Questions (Intermediate)

1. How do you handle authentication in Playwright tests?

Authentication can be handled by saving and reusing cookies, local storage, or session storage between tests. Playwright also supports context isolation, allowing you to reuse authenticated states across multiple tests.

2. What is the purpose of the Playwright Test Runner?

The Playwright Test Runner is designed to run tests written specifically for Playwright, providing features like parallel test execution, detailed reporting, and integrations with popular CI/CD tools.

3. How do you perform network interception in Playwright?

Network interception can be performed using the page.route method, allowing you to intercept and modify network requests and responses. This is useful for mocking APIs or simulating different network conditions.

4. What is CodeGen in Playwright?

CodeGen is a powerful feature in Playwright that helps you generate scripts by recording your browser interactions. It simplifies the process of creating automated tests or scripts by capturing your actions and converting them into Playwright code, which you can then customize and extend as needed. This feature is particularly useful for those who are new to Playwright or for quickly prototyping tests.

Key Features of CodeGen:

  • Automatic Code Generation: Generates Playwright code based on your interactions with a web page.
  • Supports Multiple Languages: You can generate code in JavaScript, TypeScript, Python, C#, and Java.
  • Interactive Recording: Records clicks, text inputs, navigations, and other interactions in real time.
  • Customizable Output: The generated code can be modified to add assertions, handle more complex interactions, or integrate with your test framework.

5. 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.

Upload a single file:

				
					await page.getByLabel('Upload file').setInputFiles('file.xlsx');
				
			

Upload multiple files:

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

Note: Passing an empty array to setInputFiles() makes it difficult to unselect the files if we are already selected.

Example:

				
					await page.getByLabel('Upload file').setInputFiles([]);
				
			

6. Explain some of the click and double click actions with its options.

To handle iFrame in Playwright we use the frameLocator() which gets the frame on a particular page in Playwright. Using frameLocator() we can perform various actions on an iFrame.

Example:

				
					const button = await page.frameLocator(‘.i_frame’).locator(‘my_button’);

				
			

7. Explain some of the click and double click actions with its options.

Handling click and double-click actions can be performed with a range of customizable options.

→ The click() action in Playwright simulates a single click on a specified element. It’s one of the most common interactions in UI testing.

Basic Syntax: await page.click(selector);

→ The dblclick() action simulates a double-click on the specified element, which can trigger different responses from single-click actions, such as selecting text or opening context menus.

Basic Syntaxawait page.dblclick(selector);

Playwright Interview Questions (Advanced)

1. What are the latest features in Playwright 2024 that enhance debugging capabilities?

The latest updates include improvements to the Trace Viewer, offering a more intuitive and performance-optimized interface for debugging complex test scenarios.

2. How do you implement component testing in Playwright?

Component testing in Playwright can be implemented by isolating UI components and testing their behavior in different states and props. The new component testing support allows for more focused and efficient UI testing.

3. Can you explain the use of the Playwright Test Generator and its recent enhancements?

The Playwright Test Generator helps create test scripts by recording user interactions. Recent enhancements include advanced suggestions and the ability to generate more robust and reliable test code.

4. What strategies do you use to ensure tests are not flaky in Playwright?

To ensure tests are not flaky, you can use Playwright’s automatic waiting, handle network requests and responses efficiently, isolate test cases, and use the built-in retry mechanism for transient failures.

5. Mention some of the helpful ways to debug Playwright tests.

(i) Running in Headfull Mode: By default, Playwright runs in headless mode. Running tests in headed mode allows you to see the browser’s actions.

How to Enable:

				
					const browser = await chromium.launch({ headless: false });
				
			

Example:

				
					const { chromium } = require('playwright');
(async () => {
  const browser = await chromium.launch({ headless: false });
  const page = await browser.newPage();
  await page.goto('https://example.com');
  // Add your test steps here
  await browser.close();
})();
				
			

(ii) Using Debugger: You can pause the test execution and open the browser’s developer tools.

How to Enable:

				
					// Add this line where you want to pause
await page.pause();
				
			

Example:

				
					await page.goto('https://example.com');
await page.pause(); // This will pause the test and open the inspector
				
			

(iii) Console Logs: Use console.log to print messages or variables to the console.

Example:

				
					const title = await page.title();
console.log(`Page title: ${title}`);
				
			

(iv) Inspecting Network Requests: Intercept and inspect network requests to debug issues related to API calls.

How to Enable:

				
					page.on('request', request => {
  console.log('Request:', request.url());
});
page.on('response', response => {
  console.log('Response:', response.url(), response.status());
});
				
			

Example:

				
					page.on('request', request => {
  console.log('Request:', request.url());
});
page.on('response', response => {
  console.log('Response:', response.url(), response.status());
});
await page.goto('https://example.com');
				
			

(v) Screenshots and Videos: Take screenshots and record videos at various stages to visually debug issues.

How to Enable:

				
					await page.screenshot({ path: 'screenshot.png' });
const context = await browser.newContext({ recordVideo: { dir: 'videos/' } });
				
			

Example:

				
					await page.goto('https://example.com');
await page.screenshot({ path: 'example.png' });
				
			

6. What are Playwright fixtures?

Fixtures in Playwright are objects that can be used in your tests to manage and share common resources such as browser instances, contexts, pages, and more. They provide a way to set up and tear down resources before and after tests run. Fixtures are a powerful feature in Playwright Test, allowing you to write clean and reusable test code.

Key Features of Fixtures:

  • Resource Management: Fixtures help manage resources like browsers, pages, contexts, and data that tests might need.
  • Scope: Fixtures can have different scopes such as test, worker, etc., defining how long the fixture lasts (e.g., per test, per worker).
  • Isolation: They ensure isolation between tests by providing fresh instances of resources for each test or group of tests.
  • Reusability: Common setup and teardown logic can be reused across multiple tests.

Example:

				
					const { test, expect } = require('@playwright/test');

test('basic test', async ({ page }) => {
  await page.goto('https://example.com');
  const title = await page.title();
  expect(title).toBe('Example Domain');
});
				
			

Note: In this example, page is a built-in fixture that provides a new page for the test.

7. How to parameterize tests in Playwright?

Parameterizing helps to run the same tests with multiple values, it is also called data-driven testing. Playwright allows parameterization, you can use data from either csv, json or plain arrays. To implement parameterization you need to use either for or foreach loop.

Example:

				
					const phoneBrands = ['Samsung', 'Apple', 'Nokia', 'Xiomi'];

for (const name of phoneBrands) {
    test(`testing with ${name}`, async () => {
        //your code
    });
}
				
			

8. How to perform drag and drop in Playwright?

Drag and Drop can be performed in multiple ways:

(i) Using dragTo() Method

The simplest way to perform drag and drop is by using the dragTo method, which allows you to specify the element you want to drag and the target element you want to drop it on.

Syntax: await sourceElement.dragTo(targetElement);

Note:

  • sourceElement: The element you want to drag.
  • targetElement: The element where you want to drop the dragged element.

Example:

				
					const source = await page.locator('#source-element');
const target = await page.locator('#target-element');

await source.dragTo(target);
				
			

(ii) Using Mouse Events for Custom Drag and Drop

If you need finer control over the drag-and-drop process, you can simulate a drag and drop using low-level mouse events like mousedown, mousemove, and mouseup.

Example: Custom Drag and Drop Using Mouse Events

				
					// Locate the elements
const source = await page.locator('#source-element');
const target = await page.locator('#target-element');

// Get the bounding box (position and dimensions) of the elements
const sourceBox = await source.boundingBox();
const targetBox = await target.boundingBox();

// Calculate the start and end positions for dragging
const startX = sourceBox.x + sourceBox.width / 2;
const startY = sourceBox.y + sourceBox.height / 2;
const endX = targetBox.x + targetBox.width / 2;
const endY = targetBox.y + targetBox.height / 2;

// Perform the drag-and-drop action using mouse events
await page.mouse.move(startX, startY);
await page.mouse.down();
await page.mouse.move(endX, endY, { steps: 10 }); // Move in steps for smoother transition
await page.mouse.up();

				
			

Related Articles

Multiple Choice Questions

Question 1. What is Playwright?

  • A) A library for backend development
  • B) A framework for mobile app development
  • C) A Node.js library to automate Chromium, Firefox, and WebKit with a single API
  • D) A JavaScript testing framework

Question 2. Which of the following browsers does Playwright support?

  • A) Chrome, Edge, Safari
  • B) Chromium, Firefox, WebKit
  • C) Chrome, Firefox, Internet Explorer
  • D) Opera, Firefox, WebKit

Question 3. What language(s) can you write Playwright tests in?

  • A) JavaScript
  • B) Python
  • C) C#
  • D) All of the above

Question 4. How do you launch a new browser instance in Playwright?

  • A) const browser = await playwright.launch();
  • B) const browser = await chromium.launch();
  • C) const browser = playwright.launch();
  • D) const browser = await browser.launch();

Question 5. What is the default timeout for Playwright actions (e.g., click, type)?

  • A) 30 seconds
  • B) 10 seconds
  • C) 60 seconds
  • D) No timeout by default

Question 6. Which method is used to create a new page in Playwright?

  • A) browser.createPage()
  • B) playwright.newPage()
  • C) browser.newPage()
  • D) chromium.newPage()

Question 7. How can you take a screenshot of a page in Playwright?

  • A) await page.screenshot({ path: 'screenshot.png' });
  • B) await page.capture({ path: 'screenshot.png' });
  • C) await page.snap({ path: 'screenshot.png' });
  • D) await page.takeScreenshot({ path: 'screenshot.png' });

Question 8. How do you close a page in Playwright?

  • A) page.close();
  • B) await browser.closePage();
  • C) browser.closePage();
  • D) await page.close();

Question 9. Which of the following is the correct method to wait for navigation after a click event?

await Promise.____([
    page.click('a#link'),
    page.waitForNavigation()
]);

  • A) all
  • B) resolve
  • C) any
  • D) allSettled

Question 10. Which of the following can be used to interact with frames in Playwright?

  • A) page.getFrameByName()
  • B) page.getFrame()
  • C) page.frame()
  • D) page.frames()

Question 11. What is the purpose of page.waitForSelector() in Playwright?

  • A) To wait for a page to load
  • B) To wait for a selector to appear in the DOM
  • C) To wait for a browser to launch
  • D) To wait for a network request to complete

Question 12. What does the page.evaluate() function do?

  • A) Evaluates the performance of a page
  • B) Retrieves the value of an element
  • C) Runs a test case on a page
  • D) Executes a function in the browser context

Question 13. How do you handle file uploads in Playwright?

  • A) await page.uploadFile(selector, filepath);
  • B) await page.upload(selector, filepath);
  • C) await page.setInputFiles(selector, filepath);
  • D) await page.sendFile(selector, filepath);

Question 14. Which method is used to block certain URLs from loading?

  • A) page.block()
  • B) page.route()
  • C) page.intercept()
  • D) page.filter()

Question 15. How do you select a dropdown option by value in Playwright?

await page.selectOption('select#options', '____');

  • A) Value
  • B) OptionValue
  • C) selectValue
  • D) chooseValue

Question 16. How do you close a browser instance in Playwright?

  • A) browser.close();
  • B) playwright.closeBrowser();
  • C) await browser.close();
  • D) await playwright.close();

Question 17. Which testing framework is officially supported by Playwright?

  • A) Jest
  • B) Mocha
  • C) Jasmine
  • D) Playwright Test

Question 18. How do you run a specific test file using Playwright Test?

  • A) npx playwright test tests/example.spec.js
  • B) npx playwright run tests/example.spec.js
  • C) npx playwright execute tests/example.spec.js
  • D) npx playwright play tests/example.spec.js

Question 19. How do you intercept a network request in Playwright?

await page.route('**/api/**', route => {
    route.____({ status: 200, body: 'Mocked Response' });
});

  • A) fulfill
  • B) complete
  • C) resolve
  • D) intercept

Question 20. Which command is used to generate a Playwright project?

  • A) npx playwright setup
  • B) npx playwright generate
  • C) npx playwright new-project
  • D) npx playwright init

Question 21. Which of the following tools is used to record and generate Playwright scripts?

  • A) Playwright Recorder
  • B) Playwright Codegen
  • C) Playwright Trace Viewer
  • D) Playwright Inspector

Question 22. How do you inspect a running Playwright test visually?

  • A) await page.inspect();
  • B) await page.debug();
  • C) await page.pause();
  • D) await page.visualize();

Question 23. Which Playwright command can be used to launch the Playwright Inspector?

  • A) npx playwright codegen
  • B) npx playwright launch-inspector
  • C) npx playwright open
  • D) npx playwright inspect

Question 24. What is the purpose of the playwright-cli package?

  • A) To run Playwright tests in a headless browser
  • B) To create Playwright projects
  • C) To manage browser installations
  • D) To provide a command-line interface for managing Playwright scripts

Question 25. How do you run Playwright tests in a headless mode?

  • A) npx playwright run --headless
  • B) npx playwright test --headless
  • C) npx playwright execute --headless
  • D) npx playwright test --mode=headless

Frequently Asked Questions

1. Is Playwright difficult?

Playwright is not that difficult as major limitations are also present in other automation testing frameworks. In this case, resolving those issues is crucial to ensure that the test procedure and outcome are unaffected.

2. What are the limitations of Playwright?

Playwright is incompatible with the built-in Safari browser and official support for Native mobile applications is still lacking. It makes use of its built-in ‘stock browser’.

3. What is the Playwright framework?

Playwright is a framework for web testing, it enables WebKit, Firefox, and Chromium testing using a single API. Playwright is designed to facilitate cross-browser web automation that is dependable, fast, capable, and evergreen.

4. Who owns the Playwright?

Microsoft released Playwright, an open-source automation library for web scraping and browser testing on January 31, 2020 since then, programmers and web developers have grown to love it.