-->

Featured

DSA Interview Question

Question: Various S orting algorithms Answer: There are various sorting algorithms, each with its own advantages and disadvantages in terms ...

Playwright Quiz

Question : Which Playwright locator is generally recommended for locating a button by its user-facing role and accessible name?

page.getByRole('button', { name: 'Submit' })

page.locator('button.submit')

page.getByTestId('submit-button')

page.locator('#submit')

Correct Answer : page.getByRole('button', { name: 'Submit' })


Question : What does Playwright automatically check before performing a standard locator.click() action?

The element is visible, stable, receives events, and is enabled

The element has a unique CSS class and an ID

The element has a specific HTML tag and text content

The element has been present in the DOM for a fixed amount of time

Correct Answer : The element is visible, stable, receives events, and is enabled


Question : What happens when a strict Playwright locator used for a single-element action matches multiple elements?

Playwright automatically clicks the first matching element

Playwright automatically clicks the last matching element

Playwright throws a strict mode violation

Playwright clicks all matching elements

Correct Answer : Playwright throws a strict mode violation


Question : Which Playwright assertion automatically retries until the locator has the expected number of matching elements?

expect(locator).toHaveCount()

expect(locator).toBeVisible()

expect(locator).toHaveAttribute()

expect(locator).toBeEnabled()

Correct Answer : expect(locator).toHaveCount()


Question : What does locator.nth(0) select in Playwright?

The last matching element

The first matching element

A random matching element

All matching elements

Correct Answer : The first matching element


Question : Which method can be used to mock a network request for a page in Playwright?

page.route()

page.mock()

page.intercept()

page.network()

Correct Answer : page.route()


Question : What is the default test ID attribute used by page.getByTestId()?

data-test

data-testid

test-id

data-pw

Correct Answer : data-testid


Question : Which Playwright feature allows tests to inspect steps, logs, errors, network requests, and DOM snapshots interactively?

UI Mode

Codegen

Trace Viewer only

Browser Console

Correct Answer : UI Mode


Question : Which locator method filters matching elements based on text contained within them?

locator.filter({ hasText: 'Product 2' })

locator.matchText('Product 2')

locator.whereText('Product 2')

locator.findText('Product 2')

Correct Answer : locator.filter({ hasText: 'Product 2' })


Question : Which API can configure a custom attribute for Playwright test IDs?

selectors.setTestIdAttribute()

selectors.setTestAttribute()

page.setTestIdAttribute()

locator.setTestIdAttribute()

Correct Answer : selectors.setTestIdAttribute()


Question : Which Playwright method is used to navigate a page to a URL?

page.goto()

page.navigate()

page.open()

page.url()

Correct Answer : page.goto()


Question : Which Playwright method is commonly used to enter text into an input field?

locator.fill()

locator.write()

locator.enter()

locator.input()

Correct Answer : locator.fill()


Question : Which Playwright locator is used to find an element by its visible text?

page.getByText()

page.getByValue()

page.getByContent()

page.getByString()

Correct Answer : page.getByText()


Question : Which Playwright locator is designed to find a form control using its associated label?

page.getByLabel()

page.getByForm()

page.getByField()

page.getByInput()

Correct Answer : page.getByLabel()


Question : Which Playwright method is used to click an element?

locator.click()

locator.tapClick()

locator.select()

locator.activate()

Correct Answer : locator.click()


Question : Which Playwright locator can be used to find an input by its placeholder text?

page.getByPlaceholder()

page.getByHint()

page.getByInputText()

page.getByPlaceholderText()

Correct Answer : page.getByPlaceholder()


Question : Which Playwright method returns the current URL of a page?

page.url()

page.currentUrl()

page.getUrl()

page.location()

Correct Answer : page.url()


Question : Which Playwright method is used to take a screenshot of a page?

page.screenshot()

page.capture()

page.takeScreenshot()

page.image()

Correct Answer : page.screenshot()


Question : Which Playwright locator is commonly used to locate an image by its alt text?

page.getByAltText()

page.getByImage()

page.getByImageText()

page.getByDescription()

Correct Answer : page.getByAltText()


Question : Which Playwright locator is used to locate an element by its title attribute?

page.getByTitle()

page.getByAttribute()

page.getByTooltip()

page.getByElementTitle()

Correct Answer : page.getByTitle()


Question : What is the main purpose of a Playwright BrowserContext?

To provide an isolated browser session with its own cookies, local storage, and session storage

To configure the browser's executable path for every test

To define the default timeout for all Playwright assertions

To store all test results in a shared browser session

Correct Answer : To provide an isolated browser session with its own cookies, local storage, and session storage


Question : Which Playwright method waits for a page to navigate to a URL matching a specified URL pattern?

page.waitForURL()

page.waitForNavigationUrl()

page.waitForLocation()

page.waitForRoute()

Correct Answer : page.waitForURL()


Question : Which Playwright method can be used to wait for a new page opened by an action such as clicking a link?

context.waitForPage()

page.waitForPopup()

page.waitForNewPage()

browser.waitForPage()

Correct Answer : page.waitForPopup()


Question : Which Playwright method is used to handle a JavaScript dialog such as alert, confirm, or prompt?

page.on('dialog', handler)

page.on('popup', handler)

page.on('alert', handler)

page.handleDialog()

Correct Answer : page.on('dialog', handler)


Question : Which Playwright API can be used to provide a mocked response for a matched network request?

route.fulfill()

route.respond()

route.mockResponse()

route.send()

Correct Answer : route.fulfill()


Question : Which Playwright API can be used to continue a network request without modifying its URL, method, or headers?

route.continue()

route.resume()

route.proceed()

route.forward()

Correct Answer : route.continue()


Question : What does the storageState option commonly allow Playwright tests to reuse?

Authentication state such as cookies and local storage

Browser executable binaries

Test screenshots and videos

Locator definitions

Correct Answer : Authentication state such as cookies and local storage


Question : Which Playwright method can be used to save the current browser context's storage state to a file?

context.storageState({ path: 'state.json' })

context.saveState('state.json')

context.exportStorage('state.json')

context.saveStorageState('state.json')

Correct Answer : context.storageState({ path: 'state.json' })


Question : Which Playwright API is used to interact with content inside an iframe?

frameLocator()

iframeLocator()

page.frameElement()

page.iframe()

Correct Answer : frameLocator()


Question : Which assertion is appropriate for verifying that an input contains a specific value?

expect(locator).toHaveValue('John')

expect(locator).toContainValue('John')

expect(locator).toEqualValue('John')

expect(locator).toMatchInput('John')

Correct Answer : expect(locator).toHaveValue('John')


Question : Which Playwright assertion verifies that an element contains the specified text?

expect(locator).toHaveText('Welcome')

expect(locator).toHaveContent('Welcome')

expect(locator).toContainTextValue('Welcome')

expect(locator).toMatchContent('Welcome')

Correct Answer : expect(locator).toHaveText('Welcome')


Question : Which Playwright method can be used to execute JavaScript in the page context?

page.evaluate()

page.executeScript()

page.runJavaScript()

page.browserEvaluate()

Correct Answer : page.evaluate()


Question : What is the purpose of the Playwright test fixture named page?

It provides an isolated Page instance for a test

It stores the test's HTML source code

It configures the browser executable

It defines the test project's retry count

Correct Answer : It provides an isolated Page instance for a test


Question : Which Playwright configuration property controls how many times a failed test is retried?

retries

retryCount

testRetries

attempts

Correct Answer : retries


Question : Which Playwright configuration property controls the number of parallel worker processes used to run tests?

workers

parallelTests

processes

concurrencyLevel

Correct Answer : workers


Question : What is the purpose of Playwright projects in the test configuration?

To run the same tests with different configurations such as browsers or environments

To create multiple browser tabs within a single page

To define multiple assertions for one test

To store screenshots separately from test results

Correct Answer : To run the same tests with different configurations such as browsers or environments


Question : Which Playwright method waits for an element to reach a specified state such as visible, hidden, attached, or detached?

locator.waitFor()

locator.waitUntil()

locator.awaitState()

locator.waitForState()

Correct Answer : locator.waitFor()


Question : Which Playwright method can be used to select an option from a standard HTML select element?

locator.selectOption()

locator.chooseOption()

locator.pickOption()

locator.select()

Correct Answer : locator.selectOption()


Question : Which Playwright method is used to upload files through a file input?

locator.setInputFiles()

locator.uploadFiles()

locator.attachFiles()

locator.setFiles()

Correct Answer : locator.setInputFiles()


Question : Which Playwright API is used to emulate a device configuration such as viewport, user agent, and device scale factor?

devices

deviceProfile()

emulateDevice()

browserDevices()

Correct Answer : devices


Question : When a Playwright locator is used with locator.all(), what does the method return?

An array of Locator objects representing the elements currently matching the locator

An array of ElementHandle objects that automatically wait for each element to appear

A single Locator that represents all matching elements

An array of DOM elements from the browser context

Correct Answer : An array of Locator objects representing the elements currently matching the locator


Question : What is a key difference between locator.all() and locator.allTextContents()?

locator.all() returns locators, while locator.allTextContents() returns the text content of matching elements

locator.all() returns text strings, while locator.allTextContents() returns locators

locator.all() waits for all elements to become visible, while locator.allTextContents() does not

locator.all() returns ElementHandle objects, while locator.allTextContents() returns DOM elements

Correct Answer : locator.all() returns locators, while locator.allTextContents() returns the text content of matching elements


Question : What happens when locator.filter({ has: anotherLocator }) is used?

It keeps elements that contain at least one descendant matching anotherLocator

It keeps elements whose own text exactly matches anotherLocator

It replaces the original locator with anotherLocator

It selects only the first element matching anotherLocator

Correct Answer : It keeps elements that contain at least one descendant matching anotherLocator


Question : In Playwright, what does expect.poll() primarily allow you to do?

Retry an arbitrary function until its returned value satisfies an assertion

Retry only locator actions until an element becomes visible

Retry a test from the beginning until it passes

Poll network requests until a response is received

Correct Answer : Retry an arbitrary function until its returned value satisfies an assertion


Question : When using page.route() with a URL pattern, which statement about route handlers is correct?

A matching request is intercepted and passed to the route handler before it continues or is fulfilled

The request is permanently blocked unless page.unroute() is called

The browser automatically retries the request before the route handler runs

The route handler is executed only after the server has returned a response

Correct Answer : A matching request is intercepted and passed to the route handler before it continues or is fulfilled


Question : What does browser.newContext({ storageState: 'auth.json' }) primarily do?

Creates a new isolated context initialized with the cookies and local storage state saved in auth.json

Launches a browser using auth.json as its executable configuration

Restores the complete browser process, including open pages, from auth.json

Creates a new context containing only the session cookies from auth.json

Correct Answer : Creates a new isolated context initialized with the cookies and local storage state saved in auth.json


Question : Which statement correctly describes Playwright's locator-based web-first assertions?

They automatically retry until the expected condition is met or the assertion timeout is reached

They execute only once and require explicit waits for dynamic elements

They wait indefinitely until the condition becomes true

They retry the entire test whenever an assertion fails

Correct Answer : They automatically retry until the expected condition is met or the assertion timeout is reached


Question : When a Playwright test creates multiple BrowserContext instances, what is the primary isolation provided between those contexts?

Each context has its own cookies, local storage, session storage, and other browser-level session data

Each context must use a different browser executable

Each context automatically runs in a separate operating-system process

Each context automatically uses a different network connection

Correct Answer : Each context has its own cookies, local storage, session storage, and other browser-level session data


Question : What does page.waitForResponse() wait for when supplied with a URL or predicate?

A network response that matches the specified URL or predicate

A page navigation that matches the specified URL or predicate

A request that has completed before the response is received

A browser context that has finished loading the specified URL

Correct Answer : A network response that matches the specified URL or predicate


Question : Why is it generally safer to start waiting for a popup before triggering the action that opens it?

It prevents a fast-opening popup from being missed by the test

It forces the popup to use the same BrowserContext as the opener

It prevents the popup from loading until the assertion completes

It guarantees that the popup will contain the expected URL

Correct Answer : It prevents a fast-opening popup from being missed by the test


Question : A login test passes locally but sometimes fails in CI because the page loads more slowly. What is the best Playwright approach?

Use a fixed page.waitForTimeout() before every action

Use web-first assertions or locator actions that automatically wait for the required state

Increase page.waitForTimeout() to several seconds

Add multiple identical clicks to ensure the action completes

Correct Answer : Use web-first assertions or locator actions that automatically wait for the required state


Question : A test needs to verify that a user is redirected to /dashboard after clicking Login. Which approach is most appropriate?

Click Login and immediately read page.url() without waiting

Click Login and use expect(page).toHaveURL(//dashboard/)

Wait for five seconds and then check page.url()

Use locator('body').toHaveText('/dashboard')

Correct Answer : Click Login and use expect(page).toHaveURL(//dashboard/)


Question : A shopping cart displays several products, and you need to click the Remove button for the product named "Laptop". What is the most reliable approach?

Click the first Remove button on the page

Use a locator for the product container and filter it by the product name, then locate its Remove button

Use page.getByRole('button', { name: 'Remove' }).first()

Use page.locator('button').nth(2)

Correct Answer : Use a locator for the product container and filter it by the product name, then locate its Remove button


Question : During a test, clicking "Export Report" opens a new browser tab. What is the appropriate way to capture that tab?

Call page.waitForTimeout() and then use browser.newPage()

Start page.waitForEvent('popup') before clicking "Export Report"

Call page.url() immediately after clicking the button

Create a second BrowserContext after clicking the button

Correct Answer : Start page.waitForEvent('popup') before clicking "Export Report"


Question : A test must verify that an API request returns HTTP status 201 when a user creates an account. Which Playwright approach is appropriate?

Use page.waitForResponse() around the action that creates the account

Use page.waitForTimeout() and inspect the browser title

Use locator.waitFor() on the API endpoint

Use page.waitForURL() with the API URL

Correct Answer : Use page.waitForResponse() around the action that creates the account


Question : A web application displays a cookie banner only for new sessions. How can a test reliably handle it without failing when it is already absent?

Check for the banner with a locator and conditionally dismiss it when present

Always click the banner's Accept button

Wait five seconds before checking the banner

Use page.reload() until the banner appears

Correct Answer : Check for the banner with a locator and conditionally dismiss it when present


Question : A test needs to verify that a downloaded PDF was created after clicking "Download". Which Playwright feature should be used?

page.waitForEvent('download')

page.waitForEvent('file')

page.waitForResponse('download')

browser.waitForFile()

Correct Answer : page.waitForEvent('download')


Question : A dashboard contains an iframe with a button named "Refresh Data". The button cannot be found using page.getByRole(). What is the likely reason and solution?

The button is inside an iframe, so use frameLocator() to locate it

The button is disabled, so use page.evaluate()

The button is hidden, so use page.waitForTimeout()

The button is outside the browser context, so create a new BrowserContext

Correct Answer : The button is inside an iframe, so use frameLocator() to locate it


Question : A test needs to verify that a user's name appears after submitting a form, but the name is loaded asynchronously. Which approach is most appropriate?

Use expect(locator).toHaveText() so the assertion can automatically retry

Use locator.textContent() immediately after submitting the form

Use page.waitForTimeout() for a fixed number of milliseconds

Read the text before submitting the form

Correct Answer : Use expect(locator).toHaveText() so the assertion can automatically retry


Question : A test suite needs to run the same tests against Chromium, Firefox, and WebKit. What is the recommended Playwright Test approach?

Create separate test files containing duplicate tests for each browser

Configure multiple Playwright projects with the required browser settings

Run all browsers manually from inside every test

Create three BrowserContexts inside every test and duplicate all assertions

Correct Answer : Configure multiple Playwright projects with the required browser settings


Question : Which code correctly verifies that a login button is visible?

expect(page.getByRole('button', { name: 'Login' })).toBeVisible()

expect(page.getByRole('button', { name: 'Login' })).visible()

page.getByRole('button', { name: 'Login' }).expectVisible()

assert(page.getByRole('button', { name: 'Login' })).isVisible()

Correct Answer : expect(page.getByRole('button', { name: 'Login' })).toBeVisible()


Question : Which code correctly fills an email input and submits a login form?

await page.getByLabel('Email').fill('user@example.com')

await page.getByRole('button', { name: 'Login' }).click()

await page.getByLabel('Email').type('user@example.com')

await page.getByRole('button', { name: 'Login' }).submit()

await page.getByLabel('Email').input('user@example.com')

await page.getByRole('button', { name: 'Login' }).click()

await page.getByLabel('Email').fill('user@example.com')

await page.getByRole('button', { name: 'Login' }).submit()

Correct Answer : await page.getByLabel('Email').fill('user@example.com')

await page.getByRole('button', { name: 'Login' }).click()


Question : Which code correctly checks that a page contains the text "Welcome"?

await expect(page.getByText('Welcome')).toBeVisible()

await page.getByText('Welcome').expectVisible()

expect(page.getByText('Welcome')).visible()

await expect(page.getByText('Welcome')).exists()

Correct Answer : await expect(page.getByText('Welcome')).toBeVisible()


Question : Which code correctly selects "India" from a standard HTML select element?

await page.locator('select#country').selectOption('India')

await page.locator('select#country').choose('India')

await page.locator('select#country').fill('India')

await page.locator('select#country').select('India')

Correct Answer : await page.locator('select#country').selectOption('India')


Question : Which code correctly waits for an API response while clicking a Save button?

const responsePromise = page.waitForResponse('**/api/save')

await page.getByRole('button', { name: 'Save' }).click()

const response = await responsePromise

const response = await page.waitForResponse('**/api/save')

await page.getByRole('button', { name: 'Save' }).click()

const responsePromise = page.waitForURL('**/api/save')

await page.getByRole('button', { name: 'Save' }).click()

const response = await responsePromise

const responsePromise = page.waitForRequest('**/api/save')

await page.getByRole('button', { name: 'Save' }).click()

const response = await responsePromise

Correct Answer : const responsePromise = page.waitForResponse('**/api/save')

await page.getByRole('button', { name: 'Save' }).click()

const response = await responsePromise


Question : Which code correctly mocks a GET request and returns a JSON response?

await page.route('**/api/products', async route => {

await route.fulfill({ status: 200, json: { products: [] } })

})

await page.mock('**/api/products', { status: 200, json: { products: [] } })

await page.route('**/api/products', async route => {

await route.respond({ status: 200, json: { products: [] } })

})

await page.intercept('**/api/products', async request => {

await request.fulfill({ status: 200, json: { products: [] } })

})

Correct Answer : await page.route('**/api/products', async route => {

await route.fulfill({ status: 200, json: { products: [] } })

})


Question : Which code correctly verifies that an input contains the value "John"?

await expect(page.getByLabel('Name')).toHaveValue('John')

await expect(page.getByLabel('Name')).toHaveText('John')

await expect(page.getByLabel('Name')).toContainText('John')

await expect(page.getByLabel('Name')).toHaveAttribute('value', 'John')

Correct Answer : await expect(page.getByLabel('Name')).toHaveValue('John')


Question : Which code correctly handles a browser popup opened by clicking a link?

const popupPromise = page.waitForEvent('popup')

await page.getByRole('link', { name: 'Open Report' }).click()

const popup = await popupPromise

const popup = await page.waitForEvent('popup')

await page.getByRole('link', { name: 'Open Report' }).click()

const popupPromise = page.waitForURL('**/report')

await page.getByRole('link', { name: 'Open Report' }).click()

const popup = await popupPromise

const popupPromise = page.waitForEvent('page')

await page.getByRole('link', { name: 'Open Report' }).click()

const popup = await popupPromise

Correct Answer : const popupPromise = page.waitForEvent('popup')

await page.getByRole('link', { name: 'Open Report' }).click()

const popup = await popupPromise


Question : Which code correctly uploads a file using a file input?

await page.locator('input[type="file"]').setInputFiles('tests/files/report.pdf')

await page.locator('input[type="file"]').upload('tests/files/report.pdf')

await page.locator('input[type="file"]').fillFile('tests/files/report.pdf')

await page.locator('input[type="file"]').setFile('tests/files/report.pdf')

Correct Answer : await page.locator('input[type="file"]').setInputFiles('tests/files/report.pdf')


Question : Which code correctly verifies that a successful login redirects the user to the dashboard?

await page.getByRole('button', { name: 'Login' }).click()

await expect(page).toHaveURL(//dashboard$/)

await page.getByRole('button', { name: 'Login' }).click()

expect(page.url()).toBe('/dashboard')

await page.getByRole('button', { name: 'Login' }).click()

await expect(page).toBeURL('/dashboard')

await page.getByRole('button', { name: 'Login' }).click()

await page.waitForURL('/dashboard')

expect(page.url()).toEqual('/dashboard')

Correct Answer : await page.getByRole('button', { name: 'Login' }).click()

await expect(page).toHaveURL(//dashboard$/)


Question : Which Playwright assertion correctly verifies that a locator contains the exact text "Order placed"?

await expect(page.getByRole('status')).toHaveText('Order placed')

await expect(page.getByRole('status')).toContainTextExact('Order placed')

await expect(page.getByRole('status')).toBeText('Order placed')

await expect(page.getByRole('status')).toHaveContent('Order placed')

Correct Answer : await expect(page.getByRole('status')).toHaveText('Order placed')


Question : Which Playwright assertion correctly verifies that a checkbox is checked?

await expect(page.getByRole('checkbox')).toBeChecked()

await expect(page.getByRole('checkbox')).toHaveCheckedState()

await expect(page.getByRole('checkbox')).toBeSelected()

await expect(page.getByRole('checkbox')).toHaveState('checked')

Correct Answer : await expect(page.getByRole('checkbox')).toBeChecked()


Question : Which Playwright assertion correctly verifies that a button is disabled?

await expect(page.getByRole('button', { name: 'Submit' })).toBeDisabled()

await expect(page.getByRole('button', { name: 'Submit' })).toHaveDisabled()

await expect(page.getByRole('button', { name: 'Submit' })).toBeInactive()

await expect(page.getByRole('button', { name: 'Submit' })).toHaveState('disabled')

Correct Answer : await expect(page.getByRole('button', { name: 'Submit' })).toBeDisabled()


Question : Which Playwright assertion correctly verifies that an input has the placeholder "Enter email"?

await expect(page.getByLabel('Email')).toHaveAttribute('placeholder', 'Enter email')

await expect(page.getByLabel('Email')).toHavePlaceholder('Enter email')

await expect(page.getByLabel('Email')).toHaveProperty('placeholder', 'Enter email')

await expect(page.getByLabel('Email')).toContainAttribute('placeholder', 'Enter email')

Correct Answer : await expect(page.getByLabel('Email')).toHaveAttribute('placeholder', 'Enter email')


Question : Which Playwright assertion correctly verifies that exactly three rows match a locator?

await expect(page.locator('table tbody tr')).toHaveCount(3)

await expect(page.locator('table tbody tr')).toHaveRows(3)

await expect(page.locator('table tbody tr')).toContainCount(3)

await expect(page.locator('table tbody tr')).toHaveLength(3)

Correct Answer : await expect(page.locator('table tbody tr')).toHaveCount(3)


Question : Which locator correctly finds a button using its accessible role and name?

page.getByRole('button', { name: 'Save' })

page.getByElement('button', 'Save')

page.findByRole('button', 'Save')

page.locatorRole('button', { name: 'Save' })

Correct Answer : page.getByRole('button', { name: 'Save' })


Question : Which locator correctly finds an input associated with the label "Username"?

page.getByLabel('Username')

page.getByText('Username')

page.getByRole('input', { label: 'Username' })

page.getByField('Username')

Correct Answer : page.getByLabel('Username')


Question : Which locator correctly finds a textbox using its placeholder?

page.getByPlaceholder('Enter username')

page.getByRole('textbox', { placeholder: 'Enter username' })

page.getByInputPlaceholder('Enter username')

page.locatorPlaceholder('Enter username')

Correct Answer : page.getByPlaceholder('Enter username')


Question : Which locator correctly targets the second matching element?

page.getByRole('button').nth(1)

page.getByRole('button').second()

page.getByRole('button').index(2)

page.getByRole('button').at(2)

Correct Answer : page.getByRole('button').nth(1)


Question : Which locator correctly finds a list item containing the text "Product A"?

page.getByRole('listitem').filter({ hasText: 'Product A' })

page.getByRole('listitem').contains('Product A')

page.getByRole('listitem', { text: 'Product A' })

page.getByText('Product A').parent('listitem')

Correct Answer : page.getByRole('listitem').filter({ hasText: 'Product A' })


Question : Which Playwright configuration option specifies the directory where test files are located?

testDir

testPath

testsDirectory

specDir

Correct Answer : testDir


Question : Which Playwright configuration option sets the base URL used by page.goto() when a relative URL is provided?

baseURL

baseUrlPath

urlBase

testBaseURL

Correct Answer : baseURL


Question : Which Playwright configuration option defines which test reporter is used?

reporter

testReporter

reporting

outputReporter

Correct Answer : reporter


Question : A test needs to locate a button whose text may change slightly but whose accessible role and name remain stable. What is the recommended approach?

Use a role-based locator with the accessible name

Use a fixed XPath based on the button's DOM position

Use a CSS selector containing generated class names

Use a fixed wait followed by clicking the first button

Correct Answer : Use a role-based locator with the accessible name


Question : A test sometimes fails because an element appears asynchronously. What is the preferred Playwright approach?

Use locator-based actions or web-first assertions that automatically wait

Add page.waitForTimeout() before every action

Use setTimeout() to delay the test

Reload the page until the element appears

Correct Answer : Use locator-based actions or web-first assertions that automatically wait


Question : A test needs to select a specific "Delete" button belonging to one particular product row. What is the best practice?

Locate the product row first, then locate its Delete button

Click the first Delete button on the page

Use a fixed nth() index based on the current page layout

Use a long XPath based on multiple ancestor levels

Correct Answer : Locate the product row first, then locate its Delete button


Question : A test needs to verify that a page displays a user's name after an API call completes. What is the best practice?

Use a web-first assertion on the user's name

Wait a fixed number of seconds before checking the name

Use a hard-coded sleep before every assertion

Use page.evaluate() to repeatedly inspect the DOM

Correct Answer : Use a web-first assertion on the user's name


Question : A test must verify that a login request succeeds and the dashboard is displayed. What is the best practice for synchronization?

Start waiting for the relevant response or page state before triggering the login action

Add a fixed five-second delay after clicking Login

Poll page.url() inside a manual loop

Reload the page after clicking Login

Correct Answer : Start waiting for the relevant response or page state before triggering the login action

PlayWright

Question: What is Playwright?

Answer:

Playwright is an open-source end-to-end automation testing framework developed by Microsoft. It supports automation of Chromium, Firefox, and WebKit browsers using a single API. Playwright provides fast, reliable, and cross-browser testing with built-in support for auto-waiting, multiple browser contexts, network interception, screenshots, videos, and parallel execution.


Question: What are the key features of Playwright?

Answer:

  • Supports Chromium, Firefox, and WebKit.
  • Cross-platform support (Windows, Linux, macOS).
  • Supports JavaScript, TypeScript, Java, Python, and .NET.
  • Automatic waiting for elements.
  • Supports multiple browser contexts.
  • Parallel test execution.
  • Network interception and API mocking.
  • Captures screenshots, videos, and traces.
  • Supports mobile device emulation.

Question: Which browsers are supported by Playwright?

Answer:

Playwright supports the following browsers:

  • Google Chrome / Chromium
  • Microsoft Edge
  • Mozilla Firefox
  • WebKit

Question: What is Browser Context in Playwright?

Answer:

A Browser Context is an isolated browser session. Multiple contexts can run inside a single browser instance without sharing cookies, cache, or local storage. It is useful for testing multiple users simultaneously.

Example: Create a browser context.

const browser = await chromium.launch();

const context = await browser.newContext();

const page = await context.newPage();

Note: Browser Contexts are lightweight and faster than launching multiple browser instances.


Question: What is the difference between Browser and Browser Context?

Answer:

Browser:

  • Represents the browser application.
  • Consumes more resources.
  • Can contain multiple browser contexts.

Browser Context:

  • Represents an isolated browser session.
  • Shares the browser process.
  • Has separate cookies, cache, and storage.

Question: What is the difference between browser, browserContext and page in Playwright?

Answer:Playwright has a hierarchy:

Browser
│
├── BrowserContext
│   │
│   ├── Page
│   ├── Page
│
├── BrowserContext
    │
    ├── Page
1. Browser
The Browser is the actual browser instance (Chromium, Firefox, or WebKit).
const browser = await chromium.launch();
Think of it as opening Chrome on your computer.

2. BrowserContext
A BrowserContext is like a new, isolated browser profile.
Each context has its own:
 Cookies
 Local Storage
 Session Storage
 Login session
 const context = await browser.newContext();

Example scenario:
Suppose you're testing a chat application.
Context 1 → User A is logged in.
Context 2 → User B is logged in.
Both users can interact without opening another browser.



3. Page
A Page represents a single browser tab.
Program: const page = await context.newPage(); Content: This is where you perform actions such as:
Program: await page.goto("https://example.com"); await page.click("#login"); await page.fill("#username", "admin"); Content:
Easy way to remember
ObjectThink of it as
BrowserChromium, Firefox, or WebKit browser instance
BrowserContextA separate Chrome profile/incognito window
PageA browser tab

Question: What is auto-waiting in Playwright?

Answer:

Playwright automatically waits for elements before performing actions. It waits until the element becomes:

  • Visible
  • Stable
  • Enabled
  • Ready to receive events

Example:

await page.locator("#login").click();

Note: Playwright automatically waits for actionability conditions before performing actions, reducing the need for explicit waits.


Question: How do you launch a browser in Playwright?

Answer:

Example: Launch Chromium browser.

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

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

    const context = await browser.newContext();

    const page = await context.newPage();

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

    await browser.close();
})();
If you're using Playwright Test
 import { test } from '@playwright/test';

test('Open Example Website', async ({ page }) => {
    await page.goto('https://example.com');
});

What each line does
const browser = await chromium.launch(); 
Launches the Chromium browser.
const context = await browser.newContext(); 
Creates a fresh browser session (like an incognito window).
const page = await context.newPage();
Opens a new browser tab.
await page.goto('https://example.com');
Navigates to the website.

"We launch the browser using chromium.launch(), create a new browser context using browser.newContext(), create a page using context.newPage(), and then navigate to the URL using page.goto()."

Question: How do you locate elements in Playwright?

Answer:

Playwright provides multiple locator strategies.

  • getByRole()
  • getByText()
  • getByLabel()
  • getByPlaceholder()
  • getByAltText()
  • getByTitle()
  • getByTestId()
  • locator()
  • CSS Selector
  • XPath
await page.getByRole('button', {
    name: 'Login'
}).click();

await page.locator("#username").fill("admin");
1. By ID
HTML:
<input id="username" />
Playwright:
await page.locator('#username');
or
await page.locator('[id="username"]');
2. By Text
HTML:
<button>Login</button>
Playwright:
await page.getByText('Login');
or
await page.locator('text=Login');
Best practice: getByText().

3.By Role (Most Recommended)
HTML:
<button>Login</button>
Playwright:
await page.getByRole('button', { name: 'Login' });
This is the recommended approach because it matches how users and assistive technologies interact with the page.

4. By CSS Selector
HTML:
<input class="user-input" />
Playwright:
await page.locator('.user-input');
or
await page.locator('input.user-input');
5. By XPath
HTML:
<button>Login</button>
Playwright:
await page.locator('//button[text()="Login"]');

Question: What is Locator in Playwright?

Answer:

A Locator represents a way to find elements on the page. It automatically retries until the element satisfies the required conditions, making tests more reliable.

Example:

const loginButton = page.locator("#login");

await loginButton.click();
Common ways to create locators

By text
page.getByText('Submit')
By role (recommended)
page.getByRole('button', { name: 'Submit' })
By label
page.getByLabel('Email')
By placeholder
page.getByPlaceholder('Enter your email')
By test ID
page.getByTestId('login-button')
By CSS selector
page.locator('.btn-primary')
page.locator('#username')
By XPath (supported but generally not recommended)
page.locator('//button[text()="Submit"]')

Content:

Locator methods :-

Once you have a locator, you can perform many actions:

 
const button = page.getByRole('button', { name: 'Save' });
await button.click();
await button.hover();
await button.fill('text');      // For input fields
await button.isVisible();
await button.textContent();
Assertions on locators
 await expect(button).toBeVisible();
await expect(button).toBeEnabled();
await expect(button).toHaveText('Save');
Chaining locators :
You can narrow down your search by chaining locators.
  
const form = page.locator('#login-form');
const submitButton = form.getByRole('button', { name: 'Login' });

await submitButton.click();
Or
page.locator('.card').locator('button').click();

Question: What is the difference between Locator and ElementHandle?

Answer:

Locator:

  • Automatically waits for elements.
  • Retries until action succeeds.
  • Recommended by Playwright.

ElementHandle:

  • Represents a fixed DOM element.
  • Does not auto-retry.
  • Can become stale if the DOM changes.

Note: Prefer using Locators instead of ElementHandle.


Question: How do you take screenshots in Playwright?

Answer:

Example: Capture the full page screenshot.

await page.screenshot({
    path: "homepage.png",
    fullPage: true
});

Question: How do you upload a file in Playwright?

Answer:

Example:

await page.locator("input[type='file']")
    .setInputFiles("sample.pdf");

Question: How do you handle alerts in Playwright?

Answer:

In Playwright, JavaScript dialogs (commonly called alerts) are handled using the page.on('dialog') event or page.once('dialog').
Playwright does not interact with browser dialogs automatically
—you must handle them, or the action that triggered the dialog will wait until the dialog is resolved.

Types of dialogs Playwright can handle:
1. Alert (alert())
2. Confirm (confirm())
3. Prompt (prompt())
4. Beforeunload (shown when leaving a page with unsaved changes)

1. Handling an Alert
An alert only has an OK button.
page.on('dialog', async dialog => {
  console.log(dialog.message());
  await dialog.accept();
});

await page.click('#alertButton');
Output: This is an alert message 

Content: 2. Handling a Confirm Dialog
A confirm dialog has OK and Cancel buttons.
Accept (OK)
page.on('dialog', async dialog => {
  console.log(dialog.type()); // confirm
  console.log(dialog.message());

  await dialog.accept();
});

await page.click('#confirmButton');
Dismiss (Cancel)
page.on('dialog', async dialog => {
  await dialog.dismiss();
});

await page.click('#confirmButton');
3. Handling a Prompt A prompt allows the user to enter text.
page.on('dialog', async dialog => {
  console.log(dialog.type()); // prompt

  await dialog.accept('John Doe');
});

await page.click('#promptButton');
This enters "John Doe" into the prompt and clicks OK.
4. Reading Dialog Information
The dialog object provides useful methods.
page.on('dialog', async dialog => {
  console.log(dialog.type());
  console.log(dialog.message());
  console.log(dialog.defaultValue());

  await dialog.accept();
});
Example output: prompt Enter your name Guest
Method Description
dialog.type() Returns the dialog type (alert, confirm, prompt, beforeunload)
dialog.message() Returns the dialog text
dialog.defaultValue() Returns the default prompt value
dialog.accept([text]) Clicks OK (optionally providing text for prompts)
dialog.dismiss() Clicks Cancel
5. Handling a beforeunload Dialog
When leaving a page that has unsaved changes:
 page.on('dialog', async dialog => {
  await dialog.accept();
});

await page.close({ runBeforeUnload: true });
Note: Playwright handles JavaScript dialogs through the dialog event. I register a page.on('dialog') or page.once('dialog') listener before triggering the dialog.
Then I inspect properties like type() and message(), and resolve it using accept() or dismiss().
For prompt dialogs, I can pass text to accept().

Question: How do you perform assertions in Playwright?

Answer:

Playwright provides built-in assertions through the expect() API.

Example:

await expect(page).toHaveTitle("Home");

await expect(page.locator("#login"))
    .toBeVisible();

Question: What is Trace Viewer in Playwright?

Answer:

Trace Viewer is a debugging tool that records every action performed during test execution, including screenshots, DOM snapshots, console logs, network requests, and timing information.

Example: Enable tracing.

await context.tracing.start({
    screenshots: true,
    snapshots: true
});

...

await context.tracing.stop({
    path: "trace.zip"
});

Note: Trace Viewer is one of the most powerful debugging features available in Playwright.

Question: How do you navigate to a URL in Playwright?

Answer:

Playwright uses the goto() method to navigate to a web page.

Example: Navigate to a website.

await page.goto("https://www.google.com");

Note: The goto() method waits until the page reaches the default load state before continuing.


Question: How do you perform mouse actions in Playwright?

Answer:

Playwright provides various mouse actions such as click, double-click, right-click, hover, and drag-and-drop.

Example: Mouse actions.

// Click
await page.locator("#btn").click();

// Double Click
await page.locator("#btn").dblclick();

// Right Click
await page.locator("#btn").click({
    button: "right"
});

// Hover
await page.locator("#menu").hover();

Question: How do you perform keyboard actions in Playwright?

Answer:

Keyboard actions are performed using the keyboard object.

Example:

await page.keyboard.type("Playwright");

await page.keyboard.press("Enter");

await page.keyboard.press("Control+A"); // for Window/Linux
await page.keyboard.press("Meta+A"); // for MacOS
await page.keyboard.press("Backspace");

Question: How do you handle dropdowns in Playwright?

Answer:

The selectOption() method is used to select values from a dropdown.

Example:

await page.locator("#country")
    .selectOption("India");

await page.locator("#country")
    .selectOption({ label: "India" });

await page.locator("#country")
    .selectOption({ index: 2 });

Question: How do you check or uncheck a checkbox in Playwright?

Answer:

Playwright provides dedicated methods to work with checkboxes.

Example:

await page.locator("#agree").check();

await page.locator("#agree").uncheck();

await expect(page.locator("#agree"))
    .toBeChecked();

Question: How do you work with radio buttons in Playwright?

Answer:

Radio buttons can be selected using the check() method.

Example:

await page.locator("#male").check();

await expect(page.locator("#male"))
    .toBeChecked();

Question: How do you handle multiple tabs in Playwright?

Answer:

Playwright uses the waitForEvent('page') method to capture newly opened tabs.

Example:

const pagePromise =
    context.waitForEvent("page");

await page.locator("#newTab").click();

const newPage = await pagePromise;

await newPage.waitForLoadState();

Question: How do you handle multiple browser windows in Playwright?

Answer:

Every newly opened browser window is represented as a new Page object.

Example:

const popupPromise =
    page.waitForEvent("popup");

await page.locator("#window")
    .click();

const popup = await popupPromise;

await popup.waitForLoadState();

Question: How do you handle file downloads in Playwright?

Answer:

Playwright provides download events for handling downloaded files.

Example:

const downloadPromise =
    page.waitForEvent("download");

await page.locator("#download")
    .click();

const download =
    await downloadPromise;

await download.saveAs("report.pdf");

Question: How do you perform drag and drop in Playwright?

Answer:

Playwright provides the dragTo() method.

Example:

await page.locator("#source")
    .dragTo(
        page.locator("#target")
    );

Question: How do you scroll a page in Playwright?

Answer:

Pages can be scrolled using JavaScript or locator methods.

Example:

await page.evaluate(() => {
    window.scrollTo(0,
    document.body.scrollHeight);
});

await page.locator("#footer")
    .scrollIntoViewIfNeeded();

Question: How do you execute JavaScript in Playwright?

Answer:

The evaluate() method executes JavaScript inside the browser.

Example:

String title =
await page.evaluate(() =>
document.title);

await page.evaluate(() => {
    localStorage.clear();
});

Question: How do you wait for an element in Playwright?

Answer:

Although Playwright automatically waits for most actions, explicit waiting is available when needed.

Example:

await page.locator("#login")
    .waitFor();

await page.waitForSelector(
    "#username"
);

Note: Explicit waits should be used only when auto-waiting is insufficient.


Question: How do you handle authentication in Playwright?

Answer:

Authentication state can be saved and reused to avoid logging in before every test.

Example:

await context.storageState({
    path: "auth.json"
});

Example: Reuse authentication.

const context =
await browser.newContext({
    storageState: "auth.json"
});

Question: What is Playwright Test Runner?

Answer:

Playwright Test Runner is the built-in testing framework that supports:

  • Parallel execution.
  • Retries.
  • Fixtures.
  • Projects.
  • HTML reports.
  • Screenshots.
  • Video recording.
  • Trace Viewer.

Question: What are Fixtures in Playwright?

Answer:

Fixtures are reusable setup and teardown components shared across tests.

Example:

test("Login Test",
async ({ page }) => {

    await page.goto(
        "https://example.com"
    );

});

Note: The page object is provided automatically by the Playwright fixture.


Question: How do you run tests in parallel in Playwright?

Answer:

Parallel execution is configured using the workers property.

Example:

export default defineConfig({

    workers: 4

});

Question: How do you retry failed tests in Playwright?

Answer:

The retries option automatically reruns failed tests.

Example:

export default defineConfig({

    retries: 2

});

Question: How do you generate an HTML report in Playwright?

Answer:

Playwright can generate rich HTML reports after test execution.

Example:

export default defineConfig({

    reporter: "html"

});

Command:

npx playwright show-report

Question: Why is Playwright preferred over Selenium?

Answer:

  • Built-in auto waiting.
  • Faster execution.
  • Supports Chromium, Firefox, and WebKit.
  • No separate browser drivers are required.
  • Supports network interception.
  • Supports parallel execution by default.
  • Built-in screenshots, videos, and tracing.
  • Provides more reliable locators.
  • Excellent debugging capabilities.

Note: Playwright is increasingly adopted for modern web application testing because of its speed, stability, and rich feature set.

Question: How do you handle dynamic web elements in Playwright?

Answer:

Dynamic web elements frequently change their attributes such as id, class, or name. In Playwright, it is recommended to use stable locators like getByRole(), getByLabel(), getByTestId(), or CSS selectors instead of dynamic IDs.

Example: Using a stable locator.

await page.getByRole("button", {
    name: "Login"
}).click();

Note: Avoid using dynamically generated IDs whenever possible.


Question: How do you handle hidden elements in Playwright?

Answer:

Hidden elements cannot be interacted with until they become visible. Playwright automatically waits for elements to become visible before performing actions.

Example:

await page.locator("#submit")
    .waitFor();

await page.locator("#submit")
    .click();

Question: How do you handle loading spinners in Playwright?

Answer:

Wait until the loading spinner disappears before interacting with page elements.

Example:

await page.locator(".loader")
    .waitFor({
        state: "hidden"
    });

await page.locator("#save")
    .click();

Question: How do you verify toast messages in Playwright?

Answer:

Locate the toast notification and verify its text using Playwright assertions.

Example:

await expect(
    page.locator(".toast")
).toHaveText(
    "Record Saved Successfully"
);

Question: How do you handle network API calls in Playwright?

Answer:

Playwright provides waitForResponse() to wait until a specific API call completes.

Example:

await Promise.all([

page.waitForResponse(
response =>
response.url().includes("/login")
&& response.status() == 200
),

page.locator("#login")
.click()

]);

Note: This is more reliable than using fixed waits.


Question: How do you mock API responses in Playwright?

Answer:

Playwright allows intercepting network requests using the route() method.

Example:

await page.route(
"**/users",
route => {

route.fulfill({

status:200,

body: JSON.stringify([
{
name:"John"
}
])

});

});

Question: How do you block unnecessary network requests in Playwright?

Answer:

Images, fonts, and advertisements can be blocked to improve execution speed.

Example:

await page.route(

"**/*.{png,jpg,jpeg,gif}",

route => route.abort()

);

Question: How do you handle stale element problems in Playwright?

Answer:

Unlike Selenium, Playwright locators automatically re-query the DOM before every action, reducing stale element issues.

Example:

await page.locator("#login")
.click();

Note: Always use Locator instead of storing ElementHandle objects.


Question: How do you capture browser console logs in Playwright?

Answer:

Console messages can be captured using the console event.

Example:

page.on("console",

msg => {

console.log(msg.text());

});

Question: How do you capture failed screenshots automatically?

Answer:

Configure Playwright Test to capture screenshots only for failed tests.

Example:

export default defineConfig({

use:{

screenshot:
"only-on-failure"

}

});

Question: How do you record videos of failed tests?

Answer:

Playwright can automatically record videos during test execution.

Example:

export default defineConfig({

use:{

video:
"retain-on-failure"

}

});

Question: How do you perform data-driven testing in Playwright?

Answer:

Use JavaScript arrays, JSON files, or CSV files to execute the same test with multiple datasets.

Example:

const users = [

"Admin",

"Manager",

"Guest"

];

for(const user of users){

test(user,

async ({page})=>{

// Test logic

});

}

Question: How do you run the same test in multiple browsers?

Answer:

Playwright Projects allow the same test to run on Chromium, Firefox, and WebKit.

Example:

projects:[

{
name:"Chromium"
},

{
name:"Firefox"
},

{
name:"WebKit"
}

]

Question: How do you handle environment-specific URLs in Playwright?

Answer:

Store URLs inside environment variables or configuration files instead of hardcoding them.

Example:

await page.goto(

process.env.BASE_URL!

);

Question: How do you organize a Playwright automation framework?

Answer:

  • Page Object Model (POM).
  • Utility classes.
  • Common fixtures.
  • Test data folder.
  • Environment configuration.
  • API helper classes.
  • Custom reporting.
  • Reusable assertions.

Note: A well-structured framework improves code reusability and maintainability.


Question: A button is visible but Playwright cannot click it. How would you troubleshoot?

Answer:

  • Verify the locator.
  • Check if another element overlaps the button.
  • Wait for animations to complete.
  • Verify the element is enabled.
  • Inspect browser console errors.
  • Use Trace Viewer for debugging.
  • Check if the button is inside an iframe.

Example:

await expect(
page.locator("#save")
).toBeVisible();

await expect(
page.locator("#save")
).toBeEnabled();

await page.locator("#save")
.click();

Question: What is the difference between page.waitForSelector() and Locator in Playwright?

Answer:

Locator is the recommended approach in Playwright because it automatically waits for elements before every action, whereas page.waitForSelector() waits only once and returns an ElementHandle.

Locator:

  • Automatically retries until the action succeeds.
  • Supports auto waiting.
  • Recommended by Playwright.

waitForSelector():

  • Returns an ElementHandle.
  • Can become stale if the DOM changes.
  • Mainly used for legacy code.

Example:

await page.locator("#login").click();

Note: Prefer Locator APIs over waitForSelector() in new projects.


Question: How do you handle Shadow DOM elements in Playwright?

Answer:

Playwright automatically pierces open Shadow DOM, so no special API is required.

Example:

await page
.locator("custom-component")
.locator("#username")
.fill("admin");

Note: Closed Shadow DOM cannot be accessed by any automation framework.


Question: How do you intercept and modify API requests in Playwright?

Answer:

The route() method allows modification of outgoing requests before they reach the server.

Example:

await page.route("**/login",

async route=>{

const request=route.request();

const data=request.postDataJSON();

data.username="Admin";

await route.continue({

postData:JSON.stringify(data)

});

});

Question: How do you verify REST API responses while testing UI in Playwright?

Answer:

Use waitForResponse() and validate the response body before continuing with UI validation.

Example:

const response=
await page.waitForResponse(

res=>res.url().includes("/users")

);

expect(response.status())
.toBe(200);

const body=
await response.json();

Question: How do you test WebSocket communication in Playwright?

Answer:

Playwright allows listening to WebSocket events for validating real-time communication.

Example:

page.on("websocket",

ws=>{

console.log(ws.url());

});

Question: How do you test file downloads without saving them to disk?

Answer:

The download object can be inspected without permanently storing the file.

Example:

const download=

await page.waitForEvent(
"download"
);

console.log(

download.suggestedFilename()

);

Question: How do you reduce flaky tests in Playwright?

Answer:

  • Use Locators instead of ElementHandle.
  • Avoid fixed waits.
  • Wait for API responses instead of UI delays.
  • Use stable selectors.
  • Use Browser Context isolation.
  • Use retries only as a last resort.
  • Review traces for failures.

Note: Most flaky tests are caused by synchronization issues rather than Playwright itself.


Question: How do you test multiple users simultaneously in Playwright?

Answer:

Create multiple Browser Contexts within the same browser instance.

Example:

const admin=

await browser.newContext();

const customer=

await browser.newContext();

const adminPage=

await admin.newPage();

const customerPage=

await customer.newPage();

Question: How do you handle authentication using API instead of UI login?

Answer:

Login using Playwright's APIRequestContext, store the authentication state, and reuse it across tests.

Example:

await request.post(

"/login",

{

data:{

username:"admin",

password:"admin"

}

});

Note: API login significantly reduces execution time.


Question: What is APIRequestContext in Playwright?

Answer:

APIRequestContext allows sending HTTP requests directly without opening a browser.

Example:

const response=

await request.get(

"/users"

);

expect(response.ok())

.toBeTruthy();

Question: How do you test responsive websites in Playwright?

Answer:

Create browser contexts with different viewport sizes or use built-in device emulation.

Example:

const context=

await browser.newContext({

viewport:{

width:390,

height:844

}

});

Question: How do you debug failed Playwright tests?

Answer:

  • Trace Viewer.
  • Inspector Mode.
  • Screenshots.
  • Videos.
  • Console Logs.
  • Network Logs.
  • PWDEBUG environment variable.

Example:

PWDEBUG=1

npx playwright test

Question: Explain the execution flow of Playwright.

Answer:

  • Playwright Test Runner starts execution.
  • Browser launches.
  • Browser Context is created.
  • Page object is initialized.
  • Locators identify elements.
  • Auto waiting ensures readiness.
  • Actions are performed.
  • Assertions validate results.
  • Reports, screenshots, videos and traces are generated.

Question: What are the best practices for designing a Playwright framework?

Answer:

  • Use Page Object Model.
  • Separate test data.
  • Create reusable utility classes.
  • Implement custom fixtures.
  • Use environment configuration.
  • Generate HTML reports.
  • Enable tracing for failures.
  • Use TypeScript instead of JavaScript.
  • Avoid duplicate locators.
  • Follow SOLID principles.

Question: Your Playwright tests pass locally but fail in Jenkins. How would you investigate?

Answer:

  • Compare browser versions.
  • Verify Playwright version.
  • Check environment variables.
  • Review Jenkins logs.
  • Inspect screenshots and traces.
  • Verify network availability.
  • Check headless-specific issues.
  • Verify permissions and file paths.
  • Look for timing differences.
  • Run the failed test with Trace Viewer.

Note: Environment differences are the most common cause of CI/CD failures.

Question: What are the different types of Assertions available in Playwright?

Answer:

Playwright provides two types of assertions:

  • Auto-Retry Assertions – Automatically wait until the expected condition becomes true.
  • Non-Retry Assertions – Immediately verify the condition without waiting.

Common Auto-Retry Assertions:

  • toBeVisible()
  • toBeHidden()
  • toBeEnabled()
  • toBeDisabled()
  • toBeEditable()
  • toBeChecked()
  • toBeEmpty()
  • toContainText()
  • toHaveText()
  • toHaveValue()
  • toHaveCount()
  • toHaveAttribute()
  • toHaveClass()
  • toHaveCSS()
  • toHaveId()
  • toHaveJSProperty()
  • toHaveRole()
  • toHaveTitle()
  • toHaveURL()

Example:

await expect(
page.locator("#login")
).toBeVisible();

Question: Explain commonly used Playwright Assertions with descriptions.

Answer:

Assertion Description
toBeVisible() Verifies that an element is visible.
toBeHidden() Verifies that an element is hidden.
toBeEnabled() Checks whether an element is enabled.
toBeDisabled() Checks whether an element is disabled.
toBeEditable() Checks whether an input field is editable.
toBeChecked() Verifies checkbox or radio button selection.
toHaveText() Verifies exact text.
toContainText() Verifies partial text.
toHaveValue() Verifies input field value.
toHaveCount() Verifies number of matching elements.
toHaveAttribute() Verifies an attribute value.
toHaveClass() Verifies CSS class.
toHaveCSS() Verifies CSS property value.
toHaveTitle() Verifies page title.
toHaveURL() Verifies current URL.

Question: What are the different Actions supported in Playwright?

Answer:

Playwright provides various built-in actions for interacting with web elements.

Action Description
click() Clicks an element.
dblclick() Double-clicks an element.
check() Selects a checkbox.
uncheck() Unselects a checkbox.
fill() Enters text into an input field.
clear() Clears an input field.
hover() Moves mouse over an element.
dragTo() Performs drag and drop.
focus() Sets focus on an element.
press() Presses a keyboard key.
pressSequentially() Types characters one by one.
setInputFiles() Uploads files.
selectOption() Selects dropdown values.
scrollIntoViewIfNeeded() Scrolls to the element.
screenshot() Takes element screenshot.

Question: What are the different Locator methods available in Playwright?

Answer:

Playwright provides multiple modern locator strategies.

Locator Description
locator() Generic locator using CSS or XPath.
getByRole() Finds elements using ARIA role.
getByText() Finds element by visible text.
getByLabel() Finds input using associated label.
getByPlaceholder() Finds element using placeholder.
getByAltText() Finds image using alt text.
getByTitle() Finds element using title attribute.
getByTestId() Finds element using test-id.
frameLocator() Locates elements inside iframe.

Question: What are the commonly used Page methods in Playwright?

Answer:

Method Description
goto() Navigate to URL.
reload() Reload current page.
goBack() Navigate back.
goForward() Navigate forward.
title() Returns page title.
url() Returns current URL.
content() Returns page HTML.
evaluate() Executes JavaScript.
waitForLoadState() Waits until page loads.
waitForResponse() Waits for API response.
waitForRequest() Waits for request.
waitForEvent() Waits for browser events.
route() Intercepts network requests.
screenshot() Takes page screenshot.
pdf() Generates PDF (Chromium).

Question: What are the commonly used Browser Context methods?

Answer:

Method Description
newPage() Creates a new page.
close() Closes browser context.
cookies() Returns cookies.
clearCookies() Deletes cookies.
grantPermissions() Grants browser permissions.
storageState() Saves authentication state.
addInitScript() Runs JavaScript before page loads.
setDefaultTimeout() Sets default timeout.

SDET interview questions

Question: Can you describe the key components of a well-structured test automation framework?

Answer:

A well-structured test automation framework should be modular, reusable, scalable, maintainable, and easy to integrate with CI/CD tools.

Key Components of a Well-Structured Test Automation Framework:

  • Modularity: The framework should follow a layered architecture such as the Page Object Model (POM) for UI automation. This separates test logic from page locators, making the framework easier to maintain.
  • Reusability: Common functionalities such as login, API requests, database operations, file handling, and utility methods should be implemented as reusable components to minimize code duplication.
  • Scalability: The framework should allow easy addition of new test cases, support multiple browsers, environments, and integrate with third-party tools without significant code changes.
  • Maintainability: Proper project structure, coding standards, logging, reporting (such as Extent Reports or Allure Reports), configuration management, and exception handling should be implemented.
  • CI/CD Integration: The framework should integrate seamlessly with CI/CD tools such as Jenkins, GitHub Actions, Azure DevOps, or GitLab CI for automated execution.

Note: A good automation framework should reduce maintenance effort, improve code reusability, support parallel execution, and generate detailed execution reports.


Question: How do you decide which framework to use for a project? What factors do you consider?

Answer:

The choice of an automation framework depends on the project's technical requirements, team expertise, application architecture, and long-term maintenance goals.

Factors for Selecting a Test Automation Framework:

  • Project Requirements: Determine whether the project requires UI testing, API testing, Mobile testing, or a combination of these.
  • Data Handling: If the application requires testing with multiple datasets, a Data-Driven Framework using Excel, JSON, CSV, or databases is a suitable choice.
  • Maintainability: For applications with frequent UI changes, using the Page Object Model (POM) improves maintainability by separating locators from test logic.
  • Parallel Execution: If execution speed is important, choose frameworks that support parallel execution such as TestNG, Playwright, or WebDriverIO.
  • Technology Stack: The automation framework should align with the application's technology stack and the team's programming expertise. For example :
    • Selenium with Java for Java-based applications.
    • Playwright or WebDriverIO for JavaScript/TypeScript projects.
    • Cypress for modern web applications.
  • CI/CD Integration: The framework should integrate easily with continuous integration tools such as Jenkins, GitHub Actions, Azure DevOps, or GitLab CI.
  • Reporting: It should support reporting tools such as Extent Reports, Allure Reports, or built-in HTML reports for better result analysis.
  • Cross-Browser Support: The framework should support execution across multiple browsers and operating systems based on project requirements.
  • Community & Support: Prefer frameworks that have active community support, regular updates, and comprehensive documentation.

Note: There is no single framework that is ideal for every project. The framework should be selected based on business requirements, application architecture, team expertise, scalability, and long-term maintenance needs.

Question: If an API request is failing with a 500 Internal Server Error, how do you debug the issue?

Answer:

A 500 Internal Server Error indicates that the request reached the server successfully, but the server encountered an unexpected error while processing it. Although the issue is typically on the server side, a tester can perform several checks to help identify the root cause.

1. Validate the API Request

  • Check Request Body: Verify that the JSON or XML payload is correctly formatted and contains all mandatory fields.
  • Check Request Headers: Ensure required headers such as Content-Type, Accept, Authorization, and custom headers are correct.
  • Verify API Endpoint: Confirm that the correct endpoint URL, HTTP method (GET, POST, PUT, DELETE, PATCH), and query/path parameters are being used.

2. Inspect the API Response

  • Check Response Body: Many APIs return detailed error messages or error codes that help identify the failure.
  • Review Server Logs: If log access is available, analyze application logs, server logs, or stack traces for detailed error information.

3. Test with Different Data

  • Execute the request using both valid and invalid payloads.
  • Verify whether the failure occurs only for specific users, roles, environments, or input data.
  • Check boundary values and special characters that might trigger server-side validation failures.

4. Debug Using API Tools

  • Execute the same request using tools like Postman, ReadyAPI, or Swagger to verify whether the issue is reproducible.
  • Compare request headers, payload, and responses with successful requests.
  • Review API monitoring tools such as New Relic, Datadog, Kibana, or Splunk for server-side exceptions.

5. Collaborate with Developers

  • Share the complete request, response, headers, payload, and timestamps with the development team.
  • Verify whether any recent deployments, configuration changes, database updates, or code modifications could have introduced the issue.
  • Provide reproducible test steps and supporting logs to help developers investigate efficiently.

Example: Verify the HTTP status code using Rest Assured.

given()
    .header("Authorization", token)
    .body(requestBody)
.when()
    .post("/users")
.then()
    .statusCode(500);

Note: A 500 Internal Server Error usually indicates a backend issue. However, testers should first verify that the request, headers, endpoint, authentication, and test data are correct before reporting the issue to the development team.

Question: If an API request is failing with a 500 Internal Server Error, how do you debug the issue?

Answer:

A 500 Internal Server Error indicates that the server encountered an unexpected error while processing the request. Although the issue is generally on the server side, a QA engineer should systematically verify the request and collect sufficient evidence before escalating it to the development team.

1. Validate the API Request

  • Verify the Request Body: Ensure the JSON/XML payload is valid and contains all mandatory fields.
  • Check Request Headers: Verify headers such as Content-Type, Accept, Authorization, and any custom headers.
  • Verify the Endpoint: Ensure the correct API endpoint, HTTP method (GET, POST, PUT, DELETE, PATCH), path parameters, and query parameters are being used.
  • Validate Authentication: Confirm that the access token, API key, or other authentication credentials are valid and not expired.

2. Analyze the API Response

  • Review the Response Body: Check whether the API returns an error code, message, or stack trace that helps identify the problem.
  • Review Response Headers: Verify server information, correlation IDs, and other diagnostic headers.
  • Check Server Logs: If log access is available, review application and server logs for detailed exception information.

3. Test with Different Data

  • Execute the request using valid and invalid payloads.
  • Verify whether the issue occurs only for specific users, roles, or environments.
  • Test boundary values and special characters to identify data-related failures.

4. Debug Using API Tools

  • Execute the same request using Postman, ReadyAPI, or Swagger to reproduce the issue.
  • Compare successful and failed requests to identify differences.
  • Review monitoring tools such as New Relic, Datadog, Kibana, or Splunk for backend exceptions.

5. Collaborate with Developers

  • Share the complete request payload, headers, response body, status code, and timestamp.
  • Provide steps to reproduce the issue consistently.
  • Check whether any recent deployments, configuration changes, or database updates could have introduced the failure.

Example: Verify the response status code using Rest Assured.

Response response =
given()
    .header("Authorization", token)
    .contentType(ContentType.JSON)
    .body(requestBody)
.when()
    .post("/users");

response.then()
    .statusCode(500);

System.out.println(response.asPrettyString());

Example: Log request and response details for debugging.

given()
    .log().all()
    .body(requestBody)
.when()
    .post("/users")
.then()
    .log().all();

Note: Before reporting a 500 Internal Server Error, always verify the request payload, endpoint, authentication, headers, and test data. Providing complete request and response logs significantly reduces debugging time for the development team.

Question: How would you handle API test automation failures in a CI/CD pipeline? How do you ensure tests are reliable?

Answer:

API test failures in a CI/CD pipeline can occur due to environmental issues, unstable test data, network problems, or application changes. The objective is to identify the root cause quickly while ensuring that the automation suite remains stable, reliable, and maintainable.

Common Causes of API Test Failures:

  • Environment Issues: API server is unavailable, incorrect base URL, or configuration problems.
  • Data Dependencies: Missing or inconsistent test data.
  • Network Issues: Timeouts, intermittent connectivity, or slow response times.
  • Application Changes: API contract changes, schema modifications, or backend defects.
  • Authentication Issues: Expired tokens or invalid credentials.

Best Practices for Handling API Test Failures:

1. Implement Retry Mechanism

  • Retry tests only for temporary failures such as network issues or timeouts.
  • Avoid retrying genuine application defects.

Example: Configure retries in TestNG.

@Test(retryAnalyzer = RetryAnalyzer.class)
public void verifyUsersAPI() {

    given()
        .when()
        .get("/users")
        .then()
        .statusCode(200);
}

Note: CI/CD tools such as Jenkins can also be configured with retry plugins.

2. Use Mock Servers

  • Use WireMock, MockServer, or Postman Mock Server to simulate API responses.
  • This minimizes dependency on unstable external services.

3. Validate the Response Before Assertions

  • Verify the response status code before validating the response body.
  • This prevents misleading assertion failures.

Example:

Response response =
given()
.when()
.get("/users");

response.then()
.statusCode(200);

response.then()
.body("size()", greaterThan(0));

4. Parameterize Environment Configuration

  • Maintain separate configurations for Development, QA, UAT, and Production.
  • Avoid hardcoding URLs and credentials.

Example:

String baseUrl =
System.getProperty(
"env",
"https://dev.api.com"
);

5. Logging and Reporting

  • Capture request payloads, response bodies, headers, execution time, and stack traces.
  • Generate detailed reports using Allure or Extent Reports.

6. Test Data Management

  • Create independent test data for every execution.
  • Clean up data after test execution whenever possible.

Note: Reliable API automation depends on stable environments, proper logging, test isolation, and minimizing external dependencies.


Question: If a test case is failing intermittently (Flaky Test), how would you debug and fix it?

Answer:

A flaky test is a test that produces inconsistent results without any application changes. It may pass in one execution and fail in another.

1. Verify the Failure Manually

  • Execute the test manually.
  • Determine whether it is an actual application defect or an automation issue.

2. Identify the Root Cause

  • Dynamic element locators.
  • Synchronization issues.
  • Slow API responses.
  • Animations or page transitions.
  • Incorrect or shared test data.
  • Parallel execution conflicts.

3. Stabilize the Test

  • Use stable CSS selectors or Relative XPath.
  • Avoid absolute XPath.
  • Replace Thread.sleep() with Explicit Waits.
  • Use retry only for transient failures.
  • Generate unique test data.
  • Reset application state after execution.

Example: Explicit Wait.

WebDriverWait wait =
new WebDriverWait(driver,
Duration.ofSeconds(10));

wait.until(
ExpectedConditions
.elementToBeClickable(
By.id("login")
));

Note: Fix the root cause instead of relying on retries, as excessive retries can hide genuine defects.


Question: If a parallel test fails intermittently, how would you debug and fix it?

Answer:

Parallel execution failures are usually caused by shared resources, synchronization problems, or improper browser session management.

1. Ensure Test Independence

  • Each test should execute independently.
  • Avoid shared users and shared test data.
  • Generate unique data for every execution.

Example: Generate unique test data.

String username =
"user_"
+ UUID.randomUUID();

2. Isolate Browser Sessions

  • Create a separate browser instance for each thread.
  • Use ThreadLocal WebDriver when executing Selenium tests in parallel.

Example:

private static ThreadLocal
<WebDriver> driver =
new ThreadLocal<>();

3. Replace Fixed Waits

  • Use Explicit Waits instead of Thread.sleep().
  • Wait only for the required condition.

4. Enable Logging and Screenshots

  • Capture screenshots on failures.
  • Store browser logs.
  • Capture API logs.
  • Record execution timestamps.

5. Maintain a Clean Test Environment

  • Reset database changes after execution.
  • Clear cookies, cache, and local storage.
  • Clean up created test data.

Example: Clear browser cookies.

driver.manage()
.deleteAllCookies();

Final Thoughts

  • Ensure tests are completely independent.
  • Use isolated browser sessions.
  • Avoid shared test data.
  • Replace fixed waits with synchronization techniques.
  • Implement proper logging and reporting.
  • Use retries only for temporary failures.
  • Clean up test data after execution.

Note: Stable automation frameworks are built on reliable synchronization, independent test execution, proper environment management, and detailed diagnostics rather than excessive retry mechanisms.

Maven Questions

Question: What is Maven and why is it used in automation project
Answer:Maven is a build automation and dependency management tool for Java-based projects. It’s used to:
  • Manage project dependencies through a centralized pom.xml file.

  • Compile, test, package and deploy applications.

  • Integrate with CI tools like Jenkins for continuous execution.

  • Ensure standard project structure and reproducibility across teams.


Question: Explain Maven lifecycle?
Answer: 

Types of Maven Lifecycles

Maven has 3 built-in lifecycles:

1️⃣ Default Lifecycle – Build & test the project
2️⃣ Clean Lifecycle – Clean old build files
3️⃣ Site Lifecycle – Generate project documentation


1️⃣ Clean Lifecycle - Deletes the target/ folder.

Used to remove previous build artifacts.

Phases:

pre-clean → clean → post-clean

Common command:

mvn clean

2️⃣ Default Lifecycle (Most Important for Selenium)

This lifecycle is used to compile code, run tests, and package the project.

Key Phases (Interview Focus)

PhasePurpose
validateChecks project structure
compileCompiles source code
testExecutes TestNG/JUnit tests
packageCreates JAR/WAR
verifyVerifies integration tests
installStores artifact in local repo
deployDeploys to remote repo

🔹 How lifecycle works (Very Important)

If you run:

mvn test

Maven automatically runs:

validate → compile → test

If you run:

mvn install

Maven runs:

validate → compile → test → package → verify → install

🔹 Selenium Example

mvn clean test

Steps executed:

  1. Deletes old target/

  2. Compiles code

  3. Executes Selenium + TestNG tests

  4. Generates reports


3️⃣ Site Lifecycle

Used to generate project documentation and reports.

Phases:

pre-site → site → post-site → site-deploy

Command:

mvn site


Quick Summary (Memorize)

  • mvn clean → removes old build

  • mvn test → runs Selenium tests

  • mvn install → saves build to local repo

  • Maven always executes previous phases automatically




Question: What is pom.xml and what are its key elements?
Answer: pom.xml (Project Object Model) is the core configuration file in Maven.

Important elements:

  • <dependencies> – To manage external libraries.

  • <build> – Custom build steps, plugins, test execution control.

  • <repositories> – Define external repo URLs (e.g., Nexus).

  • <properties> – Project-level config (e.g., Java version).

  • <profiles> – For managing different environments (dev, QA, prod).


Question: How do you manage dependencies in Maven?
Answer:Dependencies are declared inside the <dependencies> tag in pom.xml.

Example:


<dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.19.0</version> </dependency>


Maven downloads these automatically from the central repository or a custom one


Question: What is the difference between compile, test, provided, and runtime scopes in Maven?
Answer: 
Scope Description
compile -- Default scope, available in all classpaths.
test -- Available only during testing.
provided -- Required for compile, but not at runtime (e.g., servlet API).
runtime -- Required only during execution, not compilation.

Question: How do you execute tests using Maven?
Answer:Use the Surefire plugin to run tests:

mvn clean test

To run a specific test suite:
mvn test -DsuiteXmlFile=testng.xml

Question: How can you skip test cases in Maven?
Answer:You can skip test execution using:

mvn install -DskipTests

This compiles tests but skips running them.

To skip compilation and execution:

mvn install -Dmaven.test.skip=true


Question: What is the difference between clean, install, validate, package, and verify?
Answer:
Command Description
clean -- Deletes target/ directory.
validate -- Checks project is correct and all needed info is available.
compile -- Compiles the source code.
test -- Runs tests using testing framework.
package -- Packages compiled code into a .jar or .war.
verify -- Runs checks on test results.
install -- Installs the package to local repo (~/.m2).

Question: How do you run TestNG XML using Maven?
Answer: 
<configuration>
    <suiteXmlFiles>
        <suiteXmlFile>testng.xml</suiteXmlFile>
    </suiteXmlFiles>
</configuration>


Question: How do you handle version conflicts in Maven?
Answer:Use the command:

mvn dependency:tree

This shows the dependency hierarchy and highlights conflicts. Use dependency management or exclusions to resolve them:

<exclusions>
  <exclusion>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
  </exclusion>
</exclusions>



Question: What is the Surefire plugin?
Answer:Apache Surefire is a Maven plugin used for executing unit and integration tests.

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>3.2.5</version>
</plugin>

Question: How do you use profiles in Maven?
Answer:Profiles are used to run Maven builds for different environments:

<profiles>
  <profile>
    <id>qa</id>
    <properties>
      <env>qa</env>
    </properties>
  </profile>
</profiles>

Activate it with:
mvn test -P qa

popular posts