Login / Register |
4 Years Playwright Experience SDET
#playwright #brillio #sdet
Posted by TechElliptica at 04 Aug 2025 ( Day(s) Before)

Which language do you use with Playwright?

Usually, Playwright support 4 languages


1 - JavaScript & Typescript

2 - Python

3 - Java

4 - C#


In our project, we use TypeScript and JavaScript with Playwright primarily because it offers the most comprehensive and up-to-date support in the Node.js ecosystem, which Playwright is built upon. Additionally, new features and enhancements are typically introduced first in the JavaScript/TypeScript packages, ensuring we stay aligned with the latest capabilities of the framework.

What is the difference between javascript and typescript

Typing System

JavaScript uses dynamic typing, meaning variable types are determined at runtime and can change as the program executes, which allows flexibility but increases the risk of runtime errors. In contrast, TypeScript uses static typing, where types are defined at compile time using type annotations, helping developers catch errors early during development.


Compilation

JavaScript is interpreted directly by web browsers and doesn't require a compilation step, making it quick to run. TypeScript, however, must be compiled into JavaScript using the TypeScript compiler (tsc) before it can be executed, as browsers do not understand TypeScript natively.


Feature Set

JavaScript supports basic object-oriented and functional programming features but lacks built-in interfaces, generics, or advanced OOP features. TypeScript extends JavaScript by adding these capabilities, enabling developers to build more structured, scalable, and maintainable applications.


Tooling and IDE Support

TypeScript offers superior tooling support, with features like IntelliSense, type checking, auto-completion, and refactoring assistance in modern editors like VS Code. JavaScript has basic support for these features but lacks the advanced static analysis and type-safety benefits TypeScript provides.


Error Detection

In JavaScript, most errors are discovered only during runtime, which may lead to bugs in production if not caught through thorough testing. TypeScript detects many potential issues during compilation, reducing runtime failures and improving overall code reliability.


I have an int array

const arr = [0,0,1,2,0,0,3,4,0,5,6,0,0,7,8,0,9]


write a javascript code to arrange all zero in the last


output should be

[1,2,3,4,5,6,7,8,9,0,0,0,0,0,0,0,0]


const arr = [0, 0, 1, 2, 0, 0, 3, 4, 0, 5, 6, 0, 0, 7, 8, 0, 9];

function moveZerosToEnd(arr) {
const result = [];
let zeroCount = 0;

for (let num of arr) {
if (num === 0) {
zeroCount++;
} else {
result.push(num);
}
}

while (zeroCount-- > 0) {
result.push(0);
}

return result;
}

const output = moveZerosToEnd(arr);
console.log(output);

I have an int array

const arr = [0,0,1,2,0,0,3,4,0,5,6,0,0,7,8,0,9]


write a javascript code to arrange all zero in the start and rest number should sort in descending order


output should be

[0,0,0,0,0,0,0,0,9,8,7,6,5,4,3,2,1]


const arr = [0, 0, 1, 2, 0, 0, 3, 4, 0, 5, 6, 0, 0, 7, 8, 0, 9];

function moveZerosToStartAndSortDesc(arr) {
let zeroCount = 0;
const nonZeros = [];

for (let i = 0; i < arr.length; i++) {
if (arr[i] === 0) {
zeroCount++;
} else {
nonZeros.push(arr[i]);
}
}

nonZeros.sort((a, b) => b - a);
const result = [];

for (let i = 0; i < zeroCount; i++) {
result.push(0);
}

for (let i = 0; i < nonZeros.length; i++) {
result.push(nonZeros[i]);
}

return result;
}

const output = moveZerosToStartAndSortDesc(arr);
console.log(output);

How to handle frame in playwright ?


Using frameLocator() (Recommended - Auto-waiting)

await page.frameLocator('#myFrame').locator('input#username').fill('Vaibhav');
  1. #myFrame is the id or selector for the <iframe>.
  2. This method is robust and automatically waits for the frame and the element.



Using page.frame() (Manual access)

const frame = page.frame({ name: 'myFrameName' });
await frame?.fill('#username', 'Vaibhav');
await frame?.click('#submit');



Using elementHandle.contentFrame()

const iframeElement = await page.$('iframe#myFrame');
const frame = await iframeElement?.contentFrame();
await frame?.click('text=Login');


How to handle parallel execution in playwright ?


1 - Using playwright.config.ts:


import { defineConfig } from'@playwright/test';
exportdefaultdefineConfig({
workers: 4// Run 4 tests in parallel
});


Command prompt/ Shell:

npx playwright test --workers=4



2 - Parallel Tests Within a File


Use test.describe.parallel() to run test cases inside the same file concurrently:


import { test, expect } from'@playwright/test';

test.describe.parallel('Parallel group', () => {
test('Test A', async ({ page }) => {
await page.goto('https://example.com/a');
});

test('Test B', async ({ page }) => {
await page.goto('https://example.com/b');
});
});



How to handle file upload in playwright ?

1. Basic File Upload

await page.goto('https://example.com/upload');
// Upload a file
await page.setInputFiles('input[type="file"]', 'tests/files/sample.pdf');

This sets the file input with a local file (must exist on disk).


2. Upload Multiple Files

await page.setInputFiles('input[type="file"]', [
'tests/files/file1.pdf',
'tests/files/file2.pdf'
]);


3. Clear File Input (Remove Uploaded Files)

await page.setInputFiles('input[type="file"]', []); // Clears selection


4. Using File Upload in a Form

await page.goto('https://example.com/upload');
await page.setInputFiles('#resume-upload', 'resume.pdf');
await page.click('#submit-button');


5. File Upload Inside an iframe

const frame = await (await page.$('iframe')).contentFrame();
await frame?.setInputFiles('input[type="file"]', 'tests/files/sample.png');


6. File Upload Using frameLocator (Recommended for Stability)

await page.frameLocator('#upload-frame')
.locator('input[type="file"]')
.setInputFiles('tests/files/data.json');


How to handle exceptions in playwright?


1. Try-Catch Block

Use this to handle any unexpected errors during a test step.

try {
await page.click('#submit');
} catch (error) {
console.error('Failed to click on submit:', error);
}


2. Handling Timeout Errors

Set custom timeouts and catch when elements are not available in time.

try {
await page.waitForSelector('#dynamic-element', { timeout: 3000 });
} catch (error) {
console.error('Element did not appear in time:', error);
}


3. Handling Page Errors (JavaScript Errors on the Page)

You can listen to page-level errors using the page.on('pageerror') event.

page.on('pageerror', (error) => {
console.error('Page error:', error);
});


4. Handling Request/Response Failures

You can listen for network-related errors.

page.on('requestfailed', request => {
console.error(`Request failed: ${request.url()} - ${request.failure()?.errorText}`);
});


5. Custom Error Handling

You can throw your own errors for specific business logic.

try {
const isVisible = await page.isVisible('#non-existent');
if (!isVisible) thrownewError('Element not visible');
} catch (error) {
console.error('Custom error:', error);
}


6. Global Error Handling in Test Frameworks

If you're using Playwright Test:

test('My test with error handling', async ({ page }) => {
try {
await page.goto('https://example.com');
await page.click('#invalid-id');
} catch (err) {
console.error('Test failed at some point:', err);
// Optionally take screenshot
await page.screenshot({ path: 'error.png' });
}
});



How to execute test cases in headless and headed mode in playwright?

1. Using the CLI


Headless Mode (default)

By default, Playwright runs tests in headless mode.

npx playwright test

You can also explicitly specify it:

npx playwright test --headed=false


Headed Mode (for debugging or visual run)

npx playwright test --headed


2. Modify in the playwright.config.ts or playwright.config.js


You can configure it permanently in your Playwright config file.


playwright.config.ts

import { defineConfig } from'@playwright/test';
exportdefaultdefineConfig({
use: {
headless: false, // set to true for headless mode
browserName: 'chromium', // or 'firefox', 'webkit'
},
});


3. Override in Individual Test Files


You can also override the headless setting in a test:

import { test, chromium } from'@playwright/test';

test('Run in headed mode explicitly', 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();
});


4. Using Environment Variables (Optional)

You can create a script in package.json for easy toggli

"scripts":{
"test:headless":"npx playwright test",
"test:headed":"npx playwright test --headed"
}


Suppose you have 2 tables


Employee

EmpID

EmpName

EmpCity

1

Ram Mohan

Pune

2

Ram Krishna

Mumbai



Record

EmpID

Salary

Department

1

30000

IT

2

40000

HR


Write me a query to find all employees salary who name starts with Ram


SELECT e.EmpName, r.Salary
FROM Employee e
INNER JOIN Record r ON e.EmpID = r.EmpID
WHERE e.EmpName LIKE 'Ram%';