Step-by-Step Guide to Install Git on MacOS

Method 1: Install Git Using Homebrew (Recommended)

Step 1: Open Terminal

Press:

  • Command (⌘) + Space
  • Type Terminal
  • Press Enter

Step 2: Check if Git is Already Installed

Run:

git --version

If Git is installed, you’ll see output like:

git version 2.45.0

If not installed, continue below.


Step 3: Install Homebrew (If Not Installed)

Run this command in Terminal:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Wait for installation to complete.


Step 4: Verify Homebrew Installation

Run:

brew --version

Example output:

Homebrew 4.3.0

Step 5: Install Git Using Homebrew

Run:

brew install git

Homebrew downloads and installs the latest Git version.


Step 6: Verify Git Installation

Run:

git --version

Example:

git version 2.45.1

Step 7: Configure Git Username

Run:

git config --global user.name "Your Name"

Example:

git config --global user.name "Deepesh Yadav"

Step 8: Configure Git Email

Run:

git config --global user.email "your-email@example.com"

Example:

git config --global user.email "deepesh@gmail.com"

Step 9: Verify Git Configuration

Run:

git config --list

Example output:

user.name=Deepesh Yadav
user.email=deepesh@gmail.com

Playwright Page Object Model (POM) – Step by Step Guide

1. What is Page Object Model (POM)?

Page Object Model (POM) is a design pattern used in test automation where:

  • Each web page is represented as a class
  • Locators and methods are stored separately from test files
  • Tests become reusable, maintainable, and readable

2. Why Use POM?

Problems Without POM

Without POM:

  • Duplicate locators everywhere
  • Hard to maintain tests
  • UI changes break multiple tests
  • Large test files become messy

Benefits of POM

✅ Reusable code
✅ Easy maintenance
✅ Better readability
✅ Centralized locators
✅ Scalable framework
✅ Cleaner tests


3. Basic Folder Structure

project/
│
├── tests/
│ └── login.spec.ts
│
├── pages/
│ └── LoginPage.ts
│
├── utils/
│
├── fixtures/
│
├── playwright.config.ts
│
├── package.json
│
└── tsconfig.json

4. Install Playwright

Step 1: Create Project

mkdir playwright-pom
cd playwright-pom

Step 2: Initialize Node Project

npm init -y

Step 3: Install Playwright

npm init playwright@latest

Select:

  • TypeScript
  • Tests folder
  • GitHub Actions (optional)

5. Understanding POM Structure

In POM:

ComponentResponsibility
Page ClassStores locators + methods
Test FileContains test scenarios
FixturesShared setup
UtilsReusable helper methods

6. Create Your First Page Object


Example Website

We will automate:

  • Login page
  • Dashboard validation

7. Create Login Page Class

File

pages/LoginPage.ts

LoginPage.ts

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

export class LoginPage {

readonly page: Page;
readonly username: Locator;
readonly password: Locator;
readonly loginBtn: Locator;
readonly dashboardText: Locator;

constructor(page: Page) {
this.page = page;

this.username = page.locator('#username');
this.password = page.locator('#password');
this.loginBtn = page.locator('#loginBtn');
this.dashboardText = page.locator('text=Dashboard');
}

async gotoLoginPage() {
await this.page.goto('https://example.com/login');
}

async enterUsername(user: string) {
await this.username.fill(user);
}

async enterPassword(pass: string) {
await this.password.fill(pass);
}

async clickLogin() {
await this.loginBtn.click();
}

async login(user: string, pass: string) {
await this.enterUsername(user);
await this.enterPassword(pass);
await this.clickLogin();
}

async verifyDashboardVisible() {
await expect(this.dashboardText).toBeVisible();
}
}

8. Create Test File

File

tests/login.spec.ts

login.spec.ts

import { test } from '@playwright/test';
import { LoginPage } from '../pages/LoginPage';

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

const loginPage = new LoginPage(page);

await loginPage.gotoLoginPage();

await loginPage.login('admin', 'admin123');

await loginPage.verifyDashboardVisible();
});

9. Execute Tests

npx playwright test

10. Run Specific Test

npx playwright test tests/login.spec.ts

11. View HTML Report

npx playwright show-report

12. Improve POM Design

Basic POM is good, but enterprise frameworks need more structure.


Better Folder Structure

project/
│
├── pages/
│ ├── LoginPage.ts
│ ├── DashboardPage.ts
│ └── BasePage.ts
│
├── tests/
│
├── fixtures/
│
├── test-data/
│
├── utils/
│
├── hooks/
│
├── api/
│
├── constants/
│
└── playwright.config.ts

13. Create Base Page

Why Base Page?

To avoid duplicate common methods:

  • click
  • fill
  • wait
  • navigate
  • screenshot

BasePage.ts

import { Page, Locator } from '@playwright/test';

export class BasePage {

readonly page: Page;

constructor(page: Page) {
this.page = page;
}

async navigate(url: string) {
await this.page.goto(url);
}

async click(locator: Locator) {
await locator.click();
}

async fill(locator: Locator, value: string) {
await locator.fill(value);
}

async getTitle() {
return await this.page.title();
}

async wait(milliseconds: number) {
await this.page.waitForTimeout(milliseconds);
}
}

14. Extend Base Page

Updated LoginPage.ts

import { Page, Locator } from '@playwright/test';
import { BasePage } from './BasePage';

export class LoginPage extends BasePage {

readonly username: Locator;
readonly password: Locator;
readonly loginBtn: Locator;

constructor(page: Page) {
super(page);

this.username = page.locator('#username');
this.password = page.locator('#password');
this.loginBtn = page.locator('#loginBtn');
}

async login(user: string, pass: string) {

await this.navigate('https://example.com/login');

await this.fill(this.username, user);

await this.fill(this.password, pass);

await this.click(this.loginBtn);
}
}

15. Create Dashboard Page

DashboardPage.ts

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

export class DashboardPage {

readonly page: Page;
readonly dashboardHeader: Locator;

constructor(page: Page) {
this.page = page;

this.dashboardHeader = page.locator('h1');
}

async verifyDashboardLoaded() {
await expect(this.dashboardHeader).toHaveText('Dashboard');
}
}

16. Updated Test

import { test } from '@playwright/test';
import { LoginPage } from '../pages/LoginPage';
import { DashboardPage } from '../pages/DashboardPage';

test('Verify Login', async ({ page }) => {

const loginPage = new LoginPage(page);
const dashboardPage = new DashboardPage(page);

await loginPage.login('admin', 'admin123');

await dashboardPage.verifyDashboardLoaded();
});

17. Best Practices for POM

1. Keep Locators Private to Page

❌ Bad

page.locator('#btn').click();

inside test files.


✅ Good

await loginPage.clickLogin();

2. Avoid Assertions Inside Page Methods

Page objects should perform actions.

Assertions should mostly remain in test files.


3. Use Meaningful Method Names

✅ Good

await loginPage.login();

❌ Bad

await loginPage.doAction1();

4. One Page = One Class

Each application page should have its own class.


5. Reuse Common Functions

Use:

  • BasePage
  • Utility classes
  • Helper functions

18. Real Enterprise POM Structure

project/
│
├── pages/
│ ├── auth/
│ │ ├── LoginPage.ts
│ │ └── ForgotPasswordPage.ts
│ │
│ ├── dashboard/
│ │ └── DashboardPage.ts
│ │
│ └── common/
│ └── BasePage.ts
│
├── tests/
│
├── fixtures/
│
├── api/
│
├── utils/
│
├── constants/
│
├── test-data/
│
├── reports/
│
└── screenshots/

19. Advanced POM Concepts

Component Object Model

Reusable UI components:

  • Navbar
  • Sidebar
  • Footer
  • Modal
  • Table

Example

export class HeaderComponent {

readonly profileIcon;
readonly logoutBtn;

constructor(page) {
this.profileIcon = page.locator('#profile');
this.logoutBtn = page.locator('#logout');
}

async logout() {
await this.profileIcon.click();
await this.logoutBtn.click();
}
}

20. POM with Fixtures

fixtures/baseTest.ts

import { test as base } from '@playwright/test';
import { LoginPage } from '../pages/LoginPage';

type MyFixtures = {
loginPage: LoginPage;
};

export const test = base.extend<MyFixtures>({
loginPage: async ({ page }, use) => {
await use(new LoginPage(page));
},
});

Usage

import { test } from '../fixtures/baseTest';

test('Login Test', async ({ loginPage }) => {

await loginPage.login('admin', 'admin123');
});

21. POM with Environment Variables

Install dotenv

npm install dotenv

.env

BASE_URL=https://example.com
USERNAME=admin
PASSWORD=admin123

playwright.config.ts

import dotenv from 'dotenv';

dotenv.config();

export default {
use: {
baseURL: process.env.BASE_URL
}
};

22. Common Mistakes in POM

❌ Huge Page Classes

Avoid:

  • 2000-line page classes

Split by:

  • Components
  • Features

❌ Hardcoded Waits

Avoid:

waitForTimeout(5000)

Use:

  • auto waiting
  • expect
  • waitForResponse

❌ Duplicate Locators

Centralize locators.


23. Industry-Level Recommendations

Recommended Stack

AreaTool
UI AutomationPlaywright
LanguageTypeScript
FrameworkPOM + Fixtures
ReportingAllure
CI/CDGitHub Actions
API TestingPlaywright API
DataJSON / Faker
Parallel RunPlaywright Workers

24. Final Enterprise Flow

Test File
↓
Page Object
↓
Base Page
↓
Playwright Engine
↓
Browser

25. Summary

POM Helps You

✅ Build scalable frameworks
✅ Reduce maintenance
✅ Improve readability
✅ Reuse code
✅ Create enterprise-level automation


26. Recommended Next Topics

After learning POM, learn:

  1. Playwright Fixtures
  2. API Testing
  3. Authentication Handling
  4. Parallel Execution
  5. Data-Driven Testing
  6. CI/CD Integration
  7. Retry Mechanism
  8. Playwright Hooks
  9. Allure Reporting
  10. Hybrid Framework Design

JavaScript Objects: Properties, Methods, Nested Objects and Copying

Objects are how JavaScript represents things: a user, an order, an API response, a page configuration, a test result. Almost every value you work with in testing, from response.json() to Playwright’s config file, is an object. In this lesson you will learn how to create objects, read and change their properties, add methods, work with nested data, loop through properties, and copy and compare objects without the reference bugs that catch so many beginners.

📖 What You’ll Learn: what an object is, object literals, reading properties with dot and bracket notation, adding, updating and deleting properties, shorthand properties and computed keys, methods, nested objects, checking whether a property exists, looping over keys and values, objects as references, copying and comparing objects, and objects versus arrays.


🧱 What Is an Object?

Definition: an object is a collection of properties, where each property is a key (a name) paired with a value. Values can be anything: strings, numbers, arrays, functions, even other objects. The usual way to create one is an object literal in curly braces.

📄 object.js

const user = {
  id: 7,
  name: "Asha Rao",
  email: "asha@sqatools.in",
  active: true,
  roles: ["tester", "admin"],
};

console.log(user);
console.log(typeof user, Array.isArray(user));
console.log(Object.keys(user).length, "properties");

⌨️ Terminal

node object.js

🖥️ Output

{
  id: 7,
  name: 'Asha Rao',
  email: 'asha@sqatools.in',
  active: true,
  roles: [ 'tester', 'admin' ]
}
object false
5 properties
  • Each property is written key: value, separated by commas. A trailing comma is allowed.
  • Keys are strings (or symbols). Quotes are optional when the key is a valid identifier: name and "name" are the same key.
  • Use objects for one record with named fields, and arrays for an ordered list of similar items.

🔑 Reading Properties: Dot vs Bracket Notation

📄 access.js

const order = { id: 501, "order-status": "shipped", total: 1299, 2026: "year key" };

console.log(order.id);                 // dot notation
console.log(order["total"]);           // bracket notation with a string
console.log(order["order-status"]);    // needed: the key contains a dash
console.log(order[2026]);              // numeric keys are converted to strings

const field = "total";
console.log(order[field]);             // needed: the key is in a variable
console.log(order.field);              // looks for a key literally called "field"
console.log(order.discount);           // missing property: undefined

⌨️ Terminal

node access.js

🖥️ Output

501
1299
shipped
year key
1299
undefined
undefined
UseWhen
obj.keyThe key is a fixed, valid identifier (most of the time)
obj["some-key"]The key has spaces, dashes or starts with a digit
obj[variable]The key is computed or stored in a variable

⚠️ Watch out: Reading a missing property gives undefined, but reading a property of that undefined throws TypeError: Cannot read properties of undefined. Use optional chaining (order.customer?.name) for data that may be missing; see the Optional Chaining lesson.


✏️ Adding, Updating and Deleting Properties

📄 modify.js

const config = { browser: "chromium" };

config.headless = true;          // add
config["retries"] = 2;           // add with brackets
config.browser = "firefox";      // update
delete config.retries;           // remove
console.log(config);

const settings = Object.freeze({ env: "qa" });
settings.env = "prod";           // ignored (throws in strict mode)
console.log(settings.env);

⌨️ Terminal

node modify.js

🖥️ Output

{ browser: 'firefox', headless: true }
qa

Objects declared with const can still be changed, because const only prevents assigning a new object to the variable. Object.freeze (next lesson) makes the object itself read-only.


✂️ Shorthand Properties and Computed Keys

When a variable has the same name as the key, you can write it once (shorthand property). Square brackets around a key let you compute its name from an expression:

📄 shorthand.js

const name = "Asha";
const role = "tester";

const longForm = { name: name, role: role };
const shortForm = { name, role };             // shorthand
console.log(longForm, shortForm);

const env = "qa";
const urls = {
  [`${env}URL`]: "https://qa.example.com",    // computed key
  [`${env}_timeout`]: 15000,
};
console.log(urls);

function pick(obj, key) {
  return { [key]: obj[key] };
}
console.log(pick({ a: 1, b: 2 }, "b"));

⌨️ Terminal

node shorthand.js

🖥️ Output

{ name: 'Asha', role: 'tester' } { name: 'Asha', role: 'tester' }
{ qaURL: 'https://qa.example.com', qa_timeout: 15000 }
{ b: 2 }

🛠️ Methods: Functions Inside Objects

Definition: a method is a property whose value is a function. Inside a method, this refers to the object the method was called on (see the this lesson).

📄 methods.js

const cart = {
  items: [],
  add(name, price, qty = 1) {           // method shorthand
    this.items.push({ name, price, qty });
    return this;                         // return this to allow chaining
  },
  total() {
    return this.items.reduce((sum, i) => sum + i.price * i.qty, 0);
  },
  summary() {
    return `${this.items.length} lines, total ₹${this.total()}`;
  },
};

cart.add("Pen", 10, 3).add("Notebook", 45);
console.log(cart.summary());
console.log(typeof cart.add);

⌨️ Terminal

node methods.js

🖥️ Output

2 lines, total ₹75
function

Returning this from a method allows chaining calls, a style you will meet in builders and in page-object methods.


🪆 Nested Objects

Real data is nested: an order has a customer, the customer has an address, the order has a list of items. Chain dots and brackets to reach inner values:

📄 nested.js

const order = {
  id: 501,
  customer: {
    name: "Asha",
    address: { city: "Pune", pin: "411001" },
  },
  items: [
    { sku: "PEN-1", price: 10, qty: 3 },
    { sku: "BOOK-9", price: 45, qty: 1 },
  ],
};

console.log(order.customer.address.city);
console.log(order.items[1].sku);
console.log(order.items.length);
console.log(order.customer.phone?.mobile ?? "no phone");

order.customer.address.city = "Mumbai";    // change a nested value
console.log(order.customer.address);

⌨️ Terminal

node nested.js

🖥️ Output

Pune
BOOK-9
2
no phone
{ city: 'Mumbai', pin: '411001' }

💡 Tip: When an API response is deeply nested, destructure the parts you need once (const { customer: { address } } = order;) instead of repeating long chains in every assertion.


🔍 Checking Whether a Property Exists

A property can exist and still hold undefined, so “is the value undefined?” and “does the key exist?” are different questions:

📄 exists.js

const user = { name: "Asha", nickname: undefined };

console.log(user.nickname === undefined, user.age === undefined);   // both true
console.log("nickname" in user, "age" in user);                    // key exists?
console.log(Object.hasOwn(user, "nickname"), Object.hasOwn(user, "toString"));
console.log("toString" in user);                                   // in also sees inherited keys

⌨️ Terminal

node exists.js

🖥️ Output

true true
true false
true false
true
CheckTrue when
obj.key !== undefinedThe key exists with a value other than undefined
"key" in objThe key exists on the object or its prototype chain
Object.hasOwn(obj, "key")The key exists on the object itself (ES2022)

🔁 Looping Through an Object

📄 loop.js

const scores = { asha: 91, ravi: 78, meera: 85 };

for (const name in scores) {
  console.log(name, scores[name]);
}

console.log(Object.keys(scores));
console.log(Object.values(scores));
console.log(Object.entries(scores));

for (const [name, score] of Object.entries(scores)) {
  console.log(`${name.padEnd(6)} ${score >= 80 ? "pass" : "fail"}`);
}

const average = Object.values(scores).reduce((a, b) => a + b, 0) / Object.keys(scores).length;
console.log("average", average.toFixed(1));

⌨️ Terminal

node loop.js

🖥️ Output

asha 91
ravi 78
meera 85
[ 'asha', 'ravi', 'meera' ]
[ 91, 78, 85 ]
[ [ 'asha', 91 ], [ 'ravi', 78 ], [ 'meera', 85 ] ]
asha   pass
ravi   fail
meera  pass
average 84.7

Object.entries combined with for...of and destructuring is the most common way to walk an object. String keys come back in insertion order (integer-like keys come first, in ascending order).


🔗 Objects Are References: Copying and Comparing

Assigning an object to another variable copies the reference, so both names point to the same object. Comparing two objects with === checks whether they are the same object, not whether they have the same contents.

📄 reference.js

const base = { env: "qa", retries: 0 };
const alias = base;
alias.retries = 3;
console.log(base.retries, alias === base);

const copy = { ...base };              // shallow copy
copy.retries = 5;
console.log(base.retries, copy.retries);

console.log({ id: 1 } === { id: 1 });   // different objects
const { isDeepStrictEqual } = require("node:util");
console.log(isDeepStrictEqual({ id: 1, tags: ["a"] }, { id: 1, tags: ["a"] }));

⌨️ Terminal

node reference.js

🖥️ Output

3 true
3 5
false
true

Spread and Object.assign make shallow copies: nested objects are still shared. The Destructuring and Spread lesson and the JSON lesson cover deep copies with structuredClone.


🧪 Tester Scenario: Build and Validate an API Payload

API tests constantly build request bodies and check response objects. This example builds a payload with methods and validates a response against expected fields:

📄 payload.js

const payloadBuilder = {
  data: { name: "Test User", role: "tester", active: true },
  with(key, value) {
    this.data = { ...this.data, [key]: value };
    return this;
  },
  build() {
    return { ...this.data, createdAt: "2026-11-23T10:00:00Z" };
  },
};

const payload = payloadBuilder.with("role", "admin").with("email", "admin@sqatools.in").build();
console.log(payload);

const response = { id: 9001, ...payload, active: "true" };   // simulated server response

const expected = { role: "admin", email: "admin@sqatools.in", active: true };
for (const [key, value] of Object.entries(expected)) {
  const ok = Object.is(response[key], value);
  console.log(`${ok ? "PASS" : "FAIL"} ${key}: expected ${JSON.stringify(value)}, got ${JSON.stringify(response[key])}`);
}
console.log("has id:", Object.hasOwn(response, "id") && typeof response.id === "number");

⌨️ Terminal

node payload.js

🖥️ Output

{
  name: 'Test User',
  role: 'admin',
  active: true,
  email: 'admin@sqatools.in',
  createdAt: '2026-11-23T10:00:00Z'
}
PASS role: expected "admin", got "admin"
PASS email: expected "admin@sqatools.in", got "admin@sqatools.in"
FAIL active: expected true, got "true"
has id: true

The check catches a classic API bug: active came back as the string "true" instead of the boolean true. Playwright’s expect(body).toMatchObject(expected) does this comparison for you.


📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Create a book object with title, author, year and tags (an array). Print the title and the number of tags.

Show answer

📄 practice1.js

const book = { title: "Clean Code", author: "Robert C. Martin", year: 2008, tags: ["craft", "quality"] };
console.log(book.title, book.tags.length);

🖥️ Output

Clean Code 2

Q2. Given const field = "price", read that property from { name: "Lamp", price: 899 }, then add a "discount-code" property with the value "SAVE10".

Show answer

📄 practice2.js

const product = { name: "Lamp", price: 899 };
const field = "price";
console.log(product[field]);
product["discount-code"] = "SAVE10";
console.log(product);

🖥️ Output

899
{ name: 'Lamp', price: 899, 'discount-code': 'SAVE10' }

Q3. Write a counter object with a count property and methods increment(), reset() and value().

Show answer

📄 practice3.js

const counter = {
  count: 0,
  increment() { this.count++; return this; },
  reset() { this.count = 0; return this; },
  value() { return this.count; },
};
counter.increment().increment().increment();
console.log(counter.value());
console.log(counter.reset().value());

🖥️ Output

3
0

Q4. Count how many properties of { a: 1, b: null, c: 0, d: "x", e: undefined } have a value that is not null or undefined.

Show answer

📄 practice4.js

const obj = { a: 1, b: null, c: 0, d: "x", e: undefined };
const count = Object.values(obj).filter((v) => v != null).length;
console.log(count);

🖥️ Output

3

Q5. Print every key: value pair of { env: "qa", browser: "firefox", workers: 4 } in the format ENV=qa.

Show answer

📄 practice5.js

const config = { env: "qa", browser: "firefox", workers: 4 };
for (const [key, value] of Object.entries(config)) {
  console.log(`${key.toUpperCase()}=${value}`);
}

🖥️ Output

ENV=qa
BROWSER=firefox
WORKERS=4

Q6. Make a copy of { name: "Asha", settings: { theme: "dark" } }, change the copy’s theme to "light", and show that the original still says "dark".

Show answer

📄 practice6.js

const original = { name: "Asha", settings: { theme: "dark" } };
const copy = { ...original, settings: { ...original.settings } };
copy.settings.theme = "light";
console.log(original.settings.theme, copy.settings.theme);

🖥️ Output

dark light

Spreading only the outer object would share settings, so the nested object must be spread too (or use structuredClone).


🧠 MCQ Quiz: Objects

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. How do you read a property whose name is stored in a variable key?
  2. What does reading a missing property return?
  3. Which is required for the key "order-id"?
  4. What does { name } mean when a variable name exists?
  5. What does delete obj.key do?
  6. What is { a: 1 } === { a: 1 }?
  7. Which check returns true only for the object’s own property, not inherited ones?
  8. What does Object.entries({ a: 1, b: 2 }) return?
  9. Inside a method called as cart.total(), what is this?
  10. Why can you change properties of an object declared with const?

💼 Interview Questions and Answers

Q1. What is the difference between dot notation and bracket notation?

Dot notation (obj.name) is shorter and used when the key is a fixed, valid identifier. Bracket notation (obj["name"]) accepts any string or expression, so it is required for keys with spaces or dashes, keys starting with digits, and dynamic keys stored in variables. Both read the same property.

Q2. How do you check if an object has a property?

Object.hasOwn(obj, key) (or the older obj.hasOwnProperty(key)) checks own properties only. key in obj also checks the prototype chain. Comparing obj[key] !== undefined fails when the property exists but holds undefined. For API assertions, hasOwn is the precise check.

Q3. How do you loop through an object’s properties?

Use Object.keys, Object.values or Object.entries with for...of, for example for (const [key, value] of Object.entries(obj)). for...in also works but includes inherited enumerable properties. Plain objects are not iterable, so for (const x of obj) throws a TypeError.

Q4. Predict the output.

📄 predict.js

const a = { x: 1 };
const b = a;
const c = { ...a };
b.x = 2;
c.x = 3;
console.log(a.x, b.x, c.x, a === b, a === c);

⌨️ Terminal

node predict.js

🖥️ Output

2 2 3 true false

b is the same object as a, so setting b.x changes a.x to 2. c is a separate copy, so its change to 3 does not affect a.


❓ Frequently Asked Questions

🤔 How do I create an empty object?

Use {}. new Object() works too but is never needed. Object.create(null) creates an object with no prototype, useful for pure dictionaries.

🤔 Can object keys be numbers?

Keys are always strings or symbols. A numeric key such as obj[1] is converted to the string “1”. Use a Map if you need keys of any type.

🤔 How do I get the number of properties in an object?

Use Object.keys(obj).length. Objects have no length property.

🤔 What is the difference between an object and JSON?

An object is a value in your program. JSON is a text format for data. JSON.stringify converts an object to JSON text and JSON.parse converts JSON text back to an object.


🏁 Summary

  • Objects store named properties: create them with { key: value } literals.
  • Use dot notation for fixed keys and bracket notation for dynamic or unusual keys.
  • Add, update and delete properties freely; methods are functions stored as properties and use this.
  • Check keys with Object.hasOwn or in, and loop with Object.entries and for...of.
  • Objects are references: copy with spread (shallow) or structuredClone (deep), and compare contents with deep equality.

Next, continue with Lesson 34: Object Methods. For extra practice, solve the JavaScript object practice programs.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Array Methods: Complete Guide (Mutating vs Non-Mutating)

JavaScript arrays have more than 30 built-in methods. The single most important thing to know about each one is whether it changes the original array (mutates it) or returns a new one. Getting that wrong causes some of the most confusing bugs in test code, such as shared test data that silently changes between tests. In this lesson you will learn the essential array methods grouped by what they do, with the modern non-mutating versions added in ES2023.

📖 What You’ll Learn: mutating versus non-mutating methods, splice for inserting, removing and replacing, slice for copying parts, concat and spread, join and toString, includes, indexOf and lastIndexOf, reverse and toReversed, fill, flat and flatMap, toSorted, toSpliced and with, Array.isArray, Array.from and Array.of, and a cheat sheet.


⚠️ Mutating vs Non-Mutating Methods

Definition: a mutating method changes the array it is called on. A non-mutating method leaves the original untouched and returns a new value (often a new array).

Mutating (change the array)Non-mutating (return something new)
push, pop, shift, unshiftslice, concat, join
splicetoSpliced (ES2023)
sorttoSorted (ES2023)
reversetoReversed (ES2023)
fill, copyWithinwith (ES2023)
Assigning arr[i] = xmap, filter, flat, flatMap, includes, indexOf, find…

📄 mutating.js

const original = [3, 1, 2];

const sortedCopy = original.toSorted();   // new array
console.log(original, sortedCopy);

const sameArray = original.sort();         // sorts in place AND returns the same array
console.log(original, sameArray === original);

⌨️ Terminal

node mutating.js

🖥️ Output

[ 3, 1, 2 ] [ 1, 2, 3 ]
[ 1, 2, 3 ] true

⚠️ Watch out: Test data defined once at the top of a file and then sorted, reversed or spliced by one test is changed for every later test. Use the non-mutating versions (or copy first with [...arr]) on shared data.


✂️ splice: Insert, Remove and Replace (Mutating)

arr.splice(start, deleteCount, ...itemsToInsert) changes the array in place and returns the removed items.

📄 splice.js

const steps = ["open", "login", "search", "logout"];

const removed = steps.splice(2, 1);                 // remove 1 item at index 2
console.log(removed, steps);

steps.splice(2, 0, "add to cart", "checkout");      // insert without removing
console.log(steps);

steps.splice(1, 1, "login with SSO");               // replace 1 item
console.log(steps);

steps.splice(-1);                                   // remove from index -1 to the end
console.log(steps);

⌨️ Terminal

node splice.js

🖥️ Output

[ 'search' ] [ 'open', 'login', 'logout' ]
[ 'open', 'login', 'add to cart', 'checkout', 'logout' ]
[ 'open', 'login with SSO', 'add to cart', 'checkout', 'logout' ]
[ 'open', 'login with SSO', 'add to cart', 'checkout' ]

Removing an item by value is a common job: find its index first, and only splice if it was found.

📄 remove-by-value.js

const tags = ["smoke", "flaky", "api"];
const i = tags.indexOf("flaky");
if (i !== -1) tags.splice(i, 1);
console.log(tags);

const j = tags.indexOf("missing");
tags.splice(j, 1);          // bug: j is -1, so this removes the LAST item
console.log(tags);

⌨️ Terminal

node remove-by-value.js

🖥️ Output

[ 'smoke', 'api' ]
[ 'smoke' ]

💡 Tip: arr.toSpliced(start, deleteCount, ...items) (ES2023) does the same as splice but returns a new array and leaves the original alone. To remove by value without mutating, arr.filter((x) => x !== value) is the simplest choice.


📎 slice: Copy Part of an Array (Non-Mutating)

arr.slice(start, end) returns a new array with the items from start up to, but not including, end. Negative indexes count from the end. It works exactly like String.prototype.slice.

📄 slice.js

const runs = ["run1", "run2", "run3", "run4", "run5"];

console.log(runs.slice(1, 3));     // index 1 and 2
console.log(runs.slice(2));        // from index 2 to the end
console.log(runs.slice(-2));       // last two
console.log(runs.slice());         // full shallow copy
console.log(runs);                 // unchanged

⌨️ Terminal

node slice.js

🖥️ Output

[ 'run2', 'run3' ]
[ 'run3', 'run4', 'run5' ]
[ 'run4', 'run5' ]
[ 'run1', 'run2', 'run3', 'run4', 'run5' ]
[ 'run1', 'run2', 'run3', 'run4', 'run5' ]
slice(start, end)splice(start, count, ...items)
Changes the original?NoYes
Second argumentEnd index (exclusive)Number of items to remove
ReturnsA new array of the selected itemsAn array of the removed items

🔗 concat, Spread, join and toString

📄 concat-join.js

const smoke = ["login", "search"];
const regression = ["refund", "export"];

console.log(smoke.concat(regression, ["extra"]));   // new array
console.log([...smoke, ...regression]);             // same with spread

console.log(smoke.join(" > "));                     // array -> string
console.log(smoke.join(""), "|", smoke.toString());
console.log([1, [2, [3]]].join("-"));               // nested arrays are stringified
console.log([null, undefined, 0].join(","));        // null/undefined become empty

⌨️ Terminal

node concat-join.js

🖥️ Output

[ 'login', 'search', 'refund', 'export', 'extra' ]
[ 'login', 'search', 'refund', 'export' ]
login > search
loginsearch | login,search
1-2,3
,,0

🔍 includes, indexOf and lastIndexOf

📄 search.js

const codes = [200, 201, 404, 500, 404];

console.log(codes.includes(404), codes.includes(302));
console.log(codes.indexOf(404), codes.lastIndexOf(404), codes.indexOf(302));
console.log(codes.includes(500, 4));                 // search from index 4

console.log([NaN].includes(NaN), [NaN].indexOf(NaN)); // includes handles NaN
console.log([{ id: 1 }].includes({ id: 1 }));        // objects compare by reference

⌨️ Terminal

node search.js

🖥️ Output

true false
2 4 -1
false
true -1
false
  • includes answers “is it there?” and returns a boolean; it also finds NaN.
  • indexOf returns the position or -1; use it when you need the index.
  • Both use strict equality, so they cannot find an object by its contents. Use find/some with a callback for that (lesson 30).

🔃 reverse, toReversed, fill and with

📄 reverse-fill.js

const order = ["first", "second", "third"];

console.log(order.toReversed(), order);   // new reversed array, original kept
order.reverse();                           // in place
console.log(order);

console.log(new Array(4).fill("pending"));
const grid = [0, 0, 0, 0, 0];
grid.fill(1, 1, 3);                        // fill indexes 1 and 2
console.log(grid);

const statuses = ["ok", "ok", "ok"];
console.log(statuses.with(1, "fail"), statuses);   // replace one item in a copy

⌨️ Terminal

node reverse-fill.js

🖥️ Output

[ 'third', 'second', 'first' ] [ 'first', 'second', 'third' ]
[ 'third', 'second', 'first' ]
[ 'pending', 'pending', 'pending', 'pending' ]
[ 0, 1, 1, 0, 0 ]
[ 'ok', 'fail', 'ok' ] [ 'ok', 'ok', 'ok' ]

⚠️ Watch out: Never fill an array with the same object if you plan to change items: new Array(3).fill({}) puts the same object in every slot. Use Array.from({ length: 3 }, () => ({})) to create separate objects.

📄 fill-trap.js

const shared = new Array(2).fill({ count: 0 });
shared[0].count++;
console.log(shared);

const separate = Array.from({ length: 2 }, () => ({ count: 0 }));
separate[0].count++;
console.log(separate);

⌨️ Terminal

node fill-trap.js

🖥️ Output

[ { count: 1 }, { count: 1 } ]
[ { count: 1 }, { count: 0 } ]

🪜 flat and flatMap

flat(depth = 1) returns a new array with nested arrays merged into it up to the given depth. flatMap(fn) maps each item to an array and flattens the result by one level.

📄 flat.js

const suites = [["login", "logout"], ["cart", ["add", "remove"]]];

console.log(suites.flat());          // one level
console.log(suites.flat(Infinity));  // all levels

const tests = [
  { name: "login", tags: ["smoke", "auth"] },
  { name: "cart", tags: ["regression"] },
];
console.log(tests.flatMap((t) => t.tags));                    // all tags
console.log(tests.flatMap((t) => t.tags.map((tag) => `${t.name}:${tag}`)));
console.log([1, 2, 3].flatMap((n) => (n % 2 ? [n, n] : [])));  // duplicate odd, drop even

⌨️ Terminal

node flat.js

🖥️ Output

[ 'login', 'logout', 'cart', [ 'add', 'remove' ] ]
[ 'login', 'logout', 'cart', 'add', 'remove' ]
[ 'smoke', 'auth', 'regression' ]
[ 'login:smoke', 'login:auth', 'cart:regression' ]
[ 1, 1, 3, 3 ]

🧰 Static Methods: Array.isArray, Array.from, Array.of

📄 static.js

console.log(Array.isArray([]), Array.isArray("abc"), Array.isArray({ length: 0 }));

console.log(Array.from("abc"));                              // iterable -> array
console.log(Array.from({ length: 3 }, (_, i) => `user${i + 1}`));
console.log(Array.from(new Map([["a", 1]])));                // Map -> [[key, value]]
console.log(Array.from([1, 2, 3], (n) => n * 10));           // with a mapping function
console.log(Array.of(5), Array.of(1, 2));

⌨️ Terminal

node static.js

🖥️ Output

true false false
[ 'a', 'b', 'c' ]
[ 'user1', 'user2', 'user3' ]
[ [ 'a', 1 ] ]
[ 10, 20, 30 ]
[ 5 ] [ 1, 2 ]

In Node.js tests you often get iterables (Sets, Maps, matchAll results). Array.from(...) or [...iterable] turns them into arrays so every array method becomes available.


📋 Array Methods Cheat Sheet

GoalMethodMutates?
Add / remove at endpush / popYes
Add / remove at startunshift / shiftYes
Insert / remove / replace in the middlesplice (or toSpliced)Yes (No)
Copy partsliceNo
Join arraysconcat, [...a, ...b]No
Array to textjoinNo
Is the value there? Where?includes, indexOf, lastIndexOfNo
Reversereverse (or toReversed)Yes (No)
Sortsort (or toSorted)Yes (No)
Replace one itemarr[i] = x (or with)Yes (No)
Flatten nested arraysflat, flatMapNo
Transform / select / combinemap, filter, reduce (next lesson)No

🧪 Tester Scenario: Keep Shared Test Data Safe

A test file defines a list of users once. Two “tests” each need a modified version. Mutating methods break the second test; non-mutating methods keep both correct:

📄 shared-data.js

const USERS = ["admin", "editor", "viewer"];

// Bad: mutating the shared array
function testRemoveViewerBad(users) {
  users.splice(users.indexOf("viewer"), 1);
  return users.length === 2;
}
function testHasThreeRoles(users) {
  return users.length === 3;
}

const shared = [...USERS];
console.log("bad:", testRemoveViewerBad(shared), testHasThreeRoles(shared));

// Good: non-mutating versions
function testRemoveViewerGood(users) {
  const withoutViewer = users.filter((u) => u !== "viewer");
  return withoutViewer.length === 2;
}
console.log("good:", testRemoveViewerGood(USERS), testHasThreeRoles(USERS));
console.log("reversed view:", USERS.toReversed(), "original:", USERS);

⌨️ Terminal

node shared-data.js

🖥️ Output

bad: true false
good: true true
reversed view: [ 'viewer', 'editor', 'admin' ] original: [ 'admin', 'editor', 'viewer' ]

💡 Tip: Object.freeze(USERS) makes accidental mutation throw an error in strict mode, which turns this kind of hidden bug into an immediate failure.


📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Remove "b" and "c" from ["a", "b", "c", "d"] with one splice call and print the removed items and the array.

Show answer

📄 practice1.js

const letters = ["a", "b", "c", "d"];
const removed = letters.splice(1, 2);
console.log(removed, letters);

🖥️ Output

[ 'b', 'c' ] [ 'a', 'd' ]

Q2. Insert "verify email" between "register" and "login" in ["register", "login", "logout"] without changing the original array.

Show answer

📄 practice2.js

const steps = ["register", "login", "logout"];
const updated = steps.toSpliced(1, 0, "verify email");
console.log(updated, steps);

🖥️ Output

[ 'register', 'verify email', 'login', 'logout' ] [ 'register', 'login', 'logout' ]

Q3. Get the middle three items of [10, 20, 30, 40, 50] with slice.

Show answer

📄 practice3.js

const values = [10, 20, 30, 40, 50];
console.log(values.slice(1, 4));

🖥️ Output

[ 20, 30, 40 ]

Q4. Turn ["2026", "11", "23"] into the string "2026-11-23" and back into an array.

Show answer

📄 practice4.js

const parts = ["2026", "11", "23"];
const date = parts.join("-");
console.log(date, date.split("-"));

🖥️ Output

2026-11-23 [ '2026', '11', '23' ]

Q5. From [{ suite: "a", tests: ["t1", "t2"] }, { suite: "b", tests: ["t3"] }], produce a flat list of all test names with flatMap.

Show answer

📄 practice5.js

const suites = [{ suite: "a", tests: ["t1", "t2"] }, { suite: "b", tests: ["t3"] }];
console.log(suites.flatMap((s) => s.tests));

🖥️ Output

[ 't1', 't2', 't3' ]

Q6. Write removeValue(arr, value) that returns a new array without any occurrence of value, and leaves the input unchanged.

Show answer

📄 practice6.js

const removeValue = (arr, value) => arr.filter((x) => x !== value);
const tags = ["smoke", "flaky", "api", "flaky"];
console.log(removeValue(tags, "flaky"), tags);

🖥️ Output

[ 'smoke', 'api' ] [ 'smoke', 'flaky', 'api', 'flaky' ]

🧠 MCQ Quiz: Array Methods

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Which method does NOT change the original array?
  2. What does splice return?
  3. What is [1, 2, 3, 4].slice(1, 3)?
  4. What does arr.splice(-1, 1) do?
  5. Which ES2023 method sorts without mutating?
  6. What is [[1, 2], [3, [4]]].flat()?
  7. What does [NaN].includes(NaN) return?
  8. What is wrong with new Array(3).fill({})?
  9. What does ["a", "b"].join("") return?
  10. What does [5, 1].sort() === original tell you?

💼 Interview Questions and Answers

Q1. What is the difference between slice and splice?

slice(start, end) is non-mutating: it returns a shallow copy of a portion, with end exclusive. splice(start, deleteCount, ...items) mutates the array: it removes and/or inserts items in place and returns the removed items. Since ES2023, toSpliced provides a non-mutating version of splice.

Q2. Which array methods mutate the original array?

push, pop, shift, unshift, splice, sort, reverse, fill and copyWithin, plus direct assignment (arr[i] = x, arr.length = 0). Everything else, including map, filter, slice, concat, flat and the ES2023 methods toSorted, toReversed, toSpliced and with, returns a new value.

Q3. How do you remove duplicates from an array?

📄 dedupe.js

const tags = ["smoke", "api", "smoke", "ui", "api"];
console.log([...new Set(tags)]);
console.log(tags.filter((t, i) => tags.indexOf(t) === i));

const users = [{ id: 1 }, { id: 2 }, { id: 1 }];
console.log([...new Map(users.map((u) => [u.id, u])).values()]);

⌨️ Terminal

node dedupe.js

🖥️ Output

[ 'smoke', 'api', 'ui' ]
[ 'smoke', 'api', 'ui' ]
[ { id: 1 }, { id: 2 } ]

A Set is simplest for primitives. For objects, deduplicate by a key, for example with a Map keyed by id.

Q4. What is the difference between flat and flatMap?

flat(depth) only flattens nested arrays (default depth 1, Infinity for all levels). flatMap(fn) first maps each element with fn and then flattens the result by exactly one level; it is equivalent to map(fn).flat() but more efficient, and returning an empty array from fn removes the element.


❓ Frequently Asked Questions

🤔 How do I empty an array in JavaScript?

Set arr.length = 0 or call arr.splice(0) to empty the same array, or assign a new empty array (arr = []) if the variable is let and nothing else holds a reference.

🤔 How do I add an item to the start of an array without mutating it?

Use spread: [newItem, ...arr]. To add at the end: [...arr, newItem].

🤔 Are toSorted and toReversed safe to use?

Yes. They are part of ES2023 and supported by Node.js 20+ and all current browsers.

🤔 What is the difference between includes and some?

includes(value) checks for an exact value with strict equality. some(fn) runs a test function, so it can match objects by their properties.


🏁 Summary

  • Know which methods mutate: push/pop/shift/unshift/splice/sort/reverse/fill change the array.
  • splice inserts, removes and replaces in place; slice copies part of an array.
  • concat/spread join arrays; join turns them into text; includes/indexOf search for values.
  • flat and flatMap flatten nested arrays.
  • ES2023 toSorted, toReversed, toSpliced and with return new arrays, ideal for shared test data.

Next, continue with Lesson 30: map, filter and reduce. For extra practice, solve the JavaScript array practice programs.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Playwright Interview Questions & Answers

🟢 1. What is Playwright?

Answer:
Playwright is an open-source automation framework developed by Microsoft for end-to-end testing of web applications.

Key Features:

  • Cross-browser support (Chromium, Firefox, WebKit)
  • Auto-waiting
  • Headless & headed execution
  • Parallel execution
  • Network interception

🟢 2. Why Playwright over Selenium?

Answer:

FeaturePlaywrightSelenium
Auto-wait✅ Built-in❌ Manual
SpeedFasterSlower
Multi-tabEasyComplex
Network mockingBuilt-inLimited
Modern supportYesLimited

🟢 3. How to install Playwright?

Answer:

npm init playwright@latest

🟢 4. Basic Test Example

import { test, expect } from '@playwright/test';test('Google search test', async ({ page }) => {
await page.goto('https://google.com');
await page.fill('input[name="q"]', 'Playwright');
await page.press('input[name="q"]', 'Enter');
await expect(page).toHaveTitle(/Playwright/);
});

🟡 5. What is Auto-Waiting?

Answer:
Playwright automatically waits for:

  • Elements to be visible
  • Elements to be stable
  • Network to be idle

Example:

await page.click('#submit'); // waits automatically

🟡 6. What are Locators?

Answer:
Locators are used to find elements.

page.locator('#id');
page.locator('.class');
page.getByText('Login');
page.getByRole('button', { name: 'Submit' });

🟡 7. Difference between locator() and page.$()

Answer:

  • locator() → Auto-wait + retry
  • page.$() → Returns immediately (not reliable)

🟡 8. How to handle dropdowns?

await page.selectOption('#dropdown', 'value1');

🟡 9. Handling checkboxes

await page.check('#checkbox');
await page.uncheck('#checkbox');

🟡 10. Handling alerts

page.on('dialog', async dialog => {
await dialog.accept();
});

🔵 11. How to handle multiple tabs?

const [newPage] = await Promise.all([
context.waitForEvent('page'),
page.click('#openTab')
]);await newPage.waitForLoadState();

🔵 12. File upload

await page.setInputFiles('#fileInput', 'test.pdf');

🔵 13. File download

const [download] = await Promise.all([
page.waitForEvent('download'),
page.click('#downloadBtn')
]);await download.saveAs('file.pdf');

🔵 14. What is Page Object Model (POM)?

Answer:
Design pattern to separate UI and test logic.

Example:

export class LoginPage {
constructor(private page) {} async login(username, password) {
await this.page.fill('#user', username);
await this.page.fill('#pass', password);
await this.page.click('#login');
}
}

🔵 15. API Testing in Playwright

import { request } from '@playwright/test';test('API Test', async () => {
const apiContext = await request.newContext();
const response = await apiContext.get('/api/users');
console.log(await response.json());
});

🔴 16. How to handle authentication?

test.use({ storageState: 'auth.json' });

Save session:

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

🔴 17. Parallel Execution

npx playwright test --workers=4

🔴 18. Retry Failed Tests

// playwright.config.ts
retries: 2

🔴 19. How to handle dynamic elements?

await page.locator('//button[text()="Submit"]').click();

Use:

  • XPath
  • contains()
  • text-based locators

🔴 20. Network Interception

await page.route('**/api/users', route => {
route.fulfill({
status: 200,
body: JSON.stringify({ name: 'Mock User' })
});
});

🧠 Advanced Scenario-Based Questions


🔥 21. Banking App Login + OTP

Solution Approach:

  • Mock OTP API
  • Use API interception
await page.route('**/otp', route => {
route.fulfill({ body: JSON.stringify({ otp: '123456' }) });
});

🔥 22. E-commerce Add to Cart Flow

await page.click('text=Add to Cart');
await expect(page.locator('#cart')).toContainText('1 item');

🔥 23. Handling Flaky Tests

Best Practices:

  • Use locators instead of selectors
  • Avoid hard waits
  • Use waitForLoadState()

🔥 24. Multi-user Session (Admin + User)

const adminContext = await browser.newContext();
const userContext = await browser.newContext();const adminPage = await adminContext.newPage();
const userPage = await userContext.newPage();

🔥 25. CI/CD Integration

Use:

  • GitHub Actions
  • Jenkins

Example:

- name: Run Playwright Tests
run: npx playwright test

26. What is Browser Context in Playwright?

Answer:
A Browser Context is an isolated session (like an incognito window).

Why important?

  • Test isolation
  • Multi-user testing
  • No shared cookies/session
const context = await browser.newContext();
const page = await context.newPage();

👉 Think: One browser → multiple contexts → multiple users


🔴 27. Difference between Browser, Context, and Page

ComponentDescription
BrowserActual browser instance
ContextIsolated session
PageTab inside context

🔴 28. How to reuse login session across tests?

Answer:
Use storage state

// Save session
await context.storageState({ path: 'auth.json' });// Reuse session
test.use({ storageState: 'auth.json' });

🔴 29. How to handle iFrames?

const frame = page.frameLocator('#frameId');
await frame.locator('#input').fill('Hello');

🔴 30. Shadow DOM handling

await page.locator('css=custom-element >> text=Submit').click();

🔴 31. How to debug Playwright tests?

Answer:

Run in debug mode:

npx playwright test --debug

Use:

await page.pause();

🔴 32. Trace Viewer in Playwright

Answer:
Playwright provides a trace viewer for debugging failures.

npx playwright show-trace trace.zip

🔴 33. How to capture screenshots?

await page.screenshot({ path: 'screenshot.png' });

Full page:

await page.screenshot({ path: 'full.png', fullPage: true });

🔴 34. How to record videos?

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

🔴 35. Handling dynamic waits (best approach)

Avoid:

await page.waitForTimeout(5000); ❌

Use:

await page.waitForSelector('#element'); ✅

🔴 36. Soft Assertions in Playwright

import { expect } from '@playwright/test';await expect.soft(page.locator('#status')).toHaveText('Success');

🔴 37. Hard vs Soft Assertions

TypeBehavior
HardStops execution
SoftContinues execution

🔴 38. How to run specific test file?

npx playwright test login.spec.ts

🔴 39. Run tests in headed mode

npx playwright test --headed

🔴 40. Environment configuration

// playwright.config.ts
use: {
baseURL: 'https://staging.example.com'
}

Usage:

await page.goto('/');

🧠 Real-Time Scenario Questions (Very Important)


🔥 41. Scenario: Element is visible but click fails

Possible reasons:

  • Overlay present
  • Element not stable
  • Animation

Solution:

await page.locator('#btn').click({ force: true });

Better:

await expect(locator).toBeVisible();
await locator.click();

🔥 42. Scenario: Test passes locally but fails in CI

Reasons:

  • Timing issues
  • Environment difference
  • Headless issues

Fix:

  • Use proper waits
  • Enable retries
  • Use trace viewer

🔥 43. Scenario: Handling infinite scrolling

await page.evaluate(() => window.scrollBy(0, window.innerHeight));

Loop until element appears:

while (!(await page.locator('#item').isVisible())) {
await page.mouse.wheel(0, 1000);
}

🔥 44. Scenario: Validate table data

const rows = page.locator('table tr');const count = await rows.count();for (let i = 0; i < count; i++) {
const text = await rows.nth(i).textContent();
console.log(text);
}

🔥 45. Scenario: Handling date picker

await page.click('#date');
await page.click('text=25');

🔥 46. Scenario: Handling authentication popup

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

🔥 47. Scenario: Drag and Drop

await page.dragAndDrop('#source', '#target');

🔥 48. Scenario: Handling file download validation

const path = await download.path();
expect(path).toContain('file');

🔥 49. Scenario: Validate API response + UI

const response = await page.waitForResponse('**/api/data');
const data = await response.json();expect(data.name).toBe('Test');

🔥 50. Scenario: Retry only failed tests

npx playwright test --retries=2

🎯 Advanced Framework Design Questions


🔷 51. How do you design a scalable Playwright framework?

Answer:

Structure:

tests/
pages/
utils/
fixtures/
config/

Best practices:

  • Use POM
  • Use fixtures
  • Use environment configs
  • Separate test data

🔷 52. What are fixtures in Playwright?

test('example', async ({ page }) => {
// page is a fixture
});

Custom fixture:

test.extend({
loginPage: async ({ page }, use) => {
await use(new LoginPage(page));
}
});

🔷 53. Data-driven testing

const users = ['user1', 'user2'];for (const user of users) {
test(`login test ${user}`, async ({ page }) => {
console.log(user);
});
}

🔷 54. Parallel vs Serial execution

test.describe.configure({ mode: 'parallel' });

Serial:

test.describe.configure({ mode: 'serial' });

🔷 55. Tags in Playwright

test('smoke test @smoke', async () => {});

Run:

npx playwright test -g "@smoke"

⚠️ Tricky Interview Questions


❓ 56. Why Playwright is faster?

  • WebSocket communication
  • No Selenium WebDriver layer
  • Direct browser control

❓ 57. Can Playwright handle multiple browsers at once?

Yes:

projects: [
{ name: 'Chromium' },
{ name: 'Firefox' },
{ name: 'WebKit' }
]

❓ 58. What happens if locator matches multiple elements?

  • Playwright throws strict mode error

Fix:

locator.first()
locator.nth(0)

❓ 59. Difference between waitForSelector and locator wait

  • locator → auto-wait
  • waitForSelector → manual wait

❓ 60. How do you reduce flakiness?

✔ Use locators
✔ Avoid hard waits
✔ Use retries
✔ Mock APIs
✔ Stable selectors

🔥 61. Scenario: Banking App – Secure Login with Token

Problem:
Login uses JWT token instead of UI login.

Solution:

  • Call API
  • Inject token into storage
const requestContext = await request.newContext();const response = await requestContext.post('/api/login', {
data: { username: 'user', password: 'pass' }
});const body = await response.json();await context.addCookies([{
name: 'token',
value: body.token,
domain: 'example.com',
path: '/'
}]);

🔥 62. Scenario: Bypass CAPTCHA (Important Interview Question)

Reality:
Playwright cannot solve CAPTCHA

Best Practice:

  • Disable CAPTCHA in test environment
  • Mock API

🔥 63. Scenario: Handling WebSocket Testing

page.on('websocket', ws => {
ws.on('framereceived', frame => {
console.log(frame.payload);
});
});

🔥 64. Scenario: Test microservices-based UI

Approach:

  • Mock dependent APIs
  • Validate UI independently
await page.route('**/orders', route => {
route.fulfill({ body: JSON.stringify({ orders: [] }) });
});

🔥 65. Scenario: Handling flaky network

await page.route('**/*', route => {
route.continue({ timeout: 10000 });
});

🔥 66. Scenario: Validate PDF download content

const buffer = await download.createReadStream();

Then parse using Node libraries


🔥 67. Scenario: Multi-language testing

await page.goto('/?lang=fr');
await expect(page.locator('h1')).toHaveText('Bonjour');

🔥 68. Scenario: Geo-location testing

const context = await browser.newContext({
geolocation: { latitude: 28.6139, longitude: 77.2090 },
permissions: ['geolocation']
});

🔥 69. Scenario: Timezone testing

const context = await browser.newContext({
timezoneId: 'Asia/Kolkata'
});

🔥 70. Scenario: Testing notifications

await context.grantPermissions(['notifications']);

🏗️ Framework Architecture Questions (Very Important)


🔷 71. How to design enterprise-level Playwright framework?

Layers:

1. Tests
2. Page Objects
3. API Layer
4. Utilities
5. Test Data
6. Config

Key Additions:

  • Logging
  • Reporting
  • Retry strategy
  • Test tagging

🔷 72. How to implement reusable utilities?

Example:

export async function login(page, user) {
await page.fill('#user', user);
}

🔷 73. Centralized test data management

Use:

  • JSON files
  • Environment variables
const data = require('./testData.json');

🔷 74. Logging in Playwright

Use console or integrate with tools like:

  • Winston
  • Custom logger

🔷 75. Reporting tools

Playwright supports:

  • HTML report
  • Allure report
npx playwright show-report

⚙️ CI/CD + DevOps Questions


🔧 76. How to run Playwright in CI/CD?

Using GitHub Actions:

name: Playwright Testson: [push]jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- run: npm install
- run: npx playwright install
- run: npx playwright test

🔧 77. How to run tests in Docker?

FROM mcr.microsoft.com/playwright:v1.40.0
WORKDIR /app
COPY . .
RUN npm install
CMD ["npx", "playwright", "test"]

🔧 78. Headless vs Headed execution

ModeUse Case
HeadlessCI/CD
HeadedDebugging

🔧 79. How to reduce execution time?

✔ Parallel execution
✔ API mocking
✔ Reuse authentication
✔ Run only changed tests


🔧 80. Sharding tests

npx playwright test --shard=1/3

🔍 Debugging & Optimization


🛠️ 81. How to debug failed tests in CI?

  • Use trace viewer
  • Capture video
  • Capture logs

🛠️ 82. Memory leak issues

Cause:

  • Not closing contexts
await context.close();

🛠️ 83. Handling slow tests

  • Remove unnecessary steps
  • Use API setup instead of UI
  • Use fixtures

🛠️ 84. Test retries strategy

retries: process.env.CI ? 2 : 0

🛠️ 85. Fail fast strategy

maxFailures: 5

🔐 Security Testing (Important)


🔒 86. How to test authentication security?

  • Validate token expiration
  • Test invalid login

🔒 87. How to test authorization?

  • Admin vs user roles
expect(await page.isVisible('#adminPanel')).toBeFalsy();

🔒 88. Sensitive data handling

  • Avoid hardcoding credentials
  • Use env variables

🔒 89. HTTPS validation

expect(page.url()).toContain('https');

🔒 90. Cookie testing

const cookies = await context.cookies();

🎯 Expert-Level Tricky Questions


❓ 91. Difference between browser.newPage() and context.newPage()

  • browser.newPage() → new default context
  • context.newPage() → controlled session

❓ 92. Why avoid waitForTimeout()?

  • Causes flaky tests
  • Slows execution

❓ 93. How Playwright handles race conditions?

  • Auto-waiting
  • Event-based execution

❓ 94. Can Playwright test backend?

Yes:

  • API testing
  • Contract testing

❓ 95. How to test file upload without UI?

await request.post('/upload', {
multipart: { file: fs.createReadStream('file.txt') }
});

❓ 96. What is test isolation?

Each test runs independently with:

  • New context
  • Clean state

❓ 97. How to handle feature flags?

await page.goto('/?feature=true');

❓ 98. How to test performance?

Basic:

const start = Date.now();
await page.goto('/');
console.log(Date.now() - start);

❓ 99. Can Playwright run without UI?

Yes → headless mode


❓ 100. When NOT to use Playwright?

  • Desktop app testing
  • Heavy performance testing (use JMeter)

Real-World Enterprise Scenarios in Playwright


🏦 1. Banking App – End-to-End Payment Flow

🎯 Problem

User logs in → adds beneficiary → transfers money → verifies transaction.

✅ Approach

  • Reuse login session
  • Mock OTP service
  • Validate UI + API

💻 Example

test('Fund transfer flow', async ({ page }) => {
await page.goto('/dashboard'); await page.click('text=Transfer');
await page.fill('#account', '123456');
await page.fill('#amount', '5000');
await page.click('#submit'); await expect(page.locator('#status')).toHaveText('Success');
});

🧠 Best Practices

  • Avoid real payment → mock API
  • Validate transaction via backend API
  • Use test accounts

🛒 2. E-Commerce – Add to Cart + Checkout

🎯 Problem

User adds product → applies coupon → completes checkout.

✅ Approach

  • Use stable locators
  • Mock payment gateway
  • Validate price calculation

💻 Example

await page.click('text=Add to Cart');
await page.fill('#coupon', 'DISCOUNT10');
await page.click('#apply');await expect(page.locator('#total')).toContainText('900');

🧠 Best Practices

  • Mock payment APIs
  • Validate cart via API
  • Use data-driven tests

👥 3. Multi-User Role Testing (Admin vs User)

🎯 Problem

Admin creates data → user verifies it.

✅ Approach

  • Use multiple browser contexts

💻 Example

const adminContext = await browser.newContext();
const userContext = await browser.newContext();const adminPage = await adminContext.newPage();
const userPage = await userContext.newPage();await adminPage.goto('/admin');
await adminPage.click('#createUser');await userPage.goto('/dashboard');

🧠 Best Practices

  • Keep sessions isolated
  • Avoid shared cookies

🔐 4. Authentication Without UI (Token-Based Login)

🎯 Problem

Login via API instead of UI (faster + stable)

✅ Approach

  • Call login API
  • Inject token

💻 Example

const response = await request.post('/api/login', {
data: { username: 'user', password: 'pass' }
});const { token } = await response.json();await context.addCookies([{ name: 'token', value: token }]);

🧠 Best Practices

  • Avoid UI login in every test
  • Store auth state

🌐 5. Microservices UI – API Mocking

🎯 Problem

Frontend depends on unstable backend services

✅ Approach

  • Mock APIs

💻 Example

await page.route('**/orders', route => {
route.fulfill({
body: JSON.stringify({ orders: [] })
});
});

🧠 Best Practices

  • Test UI independently
  • Simulate edge cases

📊 6. Data Validation Between UI and API

🎯 Problem

Ensure UI data matches backend response

💻 Example

const response = await page.waitForResponse('**/api/user');
const apiData = await response.json();const uiText = await page.locator('#username').textContent();expect(uiText).toBe(apiData.name);

🧠 Best Practices

  • Validate critical fields
  • Avoid over-validating

📱 7. Mobile Device Testing

🎯 Problem

Test responsive UI

💻 Example

import { devices } from '@playwright/test';test.use(devices['iPhone 13']);

🧠 Best Practices

  • Test key flows only
  • Avoid duplicating all tests

📦 8. File Upload & Download Validation

🎯 Problem

Upload invoice → download receipt → verify

💻 Example

await page.setInputFiles('#upload', 'invoice.pdf');const [download] = await Promise.all([
page.waitForEvent('download'),
page.click('#download')
]);

🧠 Best Practices

  • Validate file name
  • Validate file content (if critical)

🔁 9. Handling Retry & Flaky Tests

🎯 Problem

Tests fail intermittently in CI

✅ Fix

retries: 2

🧠 Best Practices

  • Fix root cause (don’t rely only on retry)
  • Use trace viewer

🧾 10. Infinite Scroll / Lazy Loading

🎯 Problem

Data loads on scroll

💻 Example

while (!(await page.locator('#item').isVisible())) {
await page.mouse.wheel(0, 1000);
}

🧠 Best Practices

  • Add exit condition
  • Avoid infinite loops

🧪 11. Feature Flag Testing

🎯 Problem

Feature enabled only for some users

💻 Example

await page.goto('/?feature=true');

🧠 Best Practices

  • Test both ON and OFF states

🌍 12. Localization Testing

🎯 Problem

App supports multiple languages

💻 Example

await page.goto('/?lang=hi');
await expect(page.locator('h1')).toHaveText('नमस्ते');

🧠 Best Practices

  • Validate key UI texts
  • Avoid full UI comparison

📍 13. Geo-Location Testing

🎯 Problem

Content varies by location

💻 Example

await context.setGeolocation({ latitude: 28.61, longitude: 77.20 });

🔄 14. Background Job Validation

🎯 Problem

Async job updates UI later

💻 Example

await expect(page.locator('#status')).toHaveText('Completed', { timeout: 10000 });

⚙️ 15. CI/CD Pipeline Execution

🎯 Problem

Run tests on every deployment

💻 Example

Using Jenkins or GitHub Actions

npx playwright test

🔥 16. Handling CAPTCHA in Enterprise Apps

❗ Reality

Automation tools should not bypass CAPTCHA

✅ Approach

  • Disable in test env
  • Use mock/stub

🧠 17. High Data Volume Testing (Tables)

🎯 Problem

Validate large tables

💻 Example

const rows = await page.locator('table tr');
expect(await rows.count()).toBeGreaterThan(0);

🔐 18. Role-Based Access Testing

🎯 Problem

User should not access admin pages

💻 Example

await page.goto('/admin');
await expect(page).toHaveURL('/unauthorized');

⚡ 19. Performance Check (Basic)

💻 Example

const start = Date.now();
await page.goto('/');
console.log(Date.now() - start);

Essential Linux Commands for Git Terminal

📁 1. File & Directory Navigation

1. pwd

Description: Shows the current working directory path.

pwd

2. ls

Description: Lists files and directories.

ls
ls -la # detailed list including hidden files

3. cd

Description: Changes directory.

cd project-folder
cd .. # move up one directory
cd ~ # go to home directory

📂 2. File & Directory Management

4. mkdir

Description: Creates a new directory.

mkdir my-repo

5. rmdir

Description: Removes an empty directory.

rmdir my-repo

6. rm

Description: Deletes files or directories.

rm file.txt
rm -r folder/ # remove directory recursively

7. cp

Description: Copies files or directories.

cp file.txt backup.txt
cp -r folder/ new-folder/

8. mv

Description: Moves or renames files.

mv file.txt newname.txt
mv file.txt folder/

📝 3. File Viewing & Editing

9. cat

Description: Displays file content.

cat README.md

10. less

Description: Views large files page by page.

less README.md

11. nano

Description: Simple terminal text editor.

nano file.txt

12. vim

Description: Advanced text editor.

vim file.txt

🔍 4. Search & Filtering

13. grep

Description: Searches text in files.

grep "function" file.js

14. find

Description: Finds files/directories.

find . -name "index.js"

⚙️ 5. Permissions & Ownership

15. chmod

Description: Changes file permissions.

chmod 755 script.sh

16. chown

Description: Changes file ownership.

chown user:user file.txt

🌐 6. Networking (Useful for Git)

17. ssh

Description: Connects securely to remote servers (used for GitHub SSH).

ssh -T git@github.com

18. curl

Description: Transfers data from URLs.

curl https://api.github.com

🧰 7. Archive & Compression

19. tar

Description: Creates/extracts archives.

tar -cvf project.tar folder/
tar -xvf project.tar

20. zip / unzip

Description: Compresses and extracts zip files.

zip -r project.zip folder/
unzip project.zip

🧪 8. System & Process Commands

21. clear

Description: Clears the terminal screen.

clear

22. history

Description: Shows previously used commands.

history

23. top

Description: Displays running processes.

top

🔄 How These Help in Git Workflow

When working with Git, these Linux commands help you:

  • Navigate to repositories (cd, ls)
  • Create/manage project files (mkdir, rm, cp)
  • Edit code before committing (nano, vim)
  • Inspect changes (cat, less)
  • Search code (grep, find)
  • Handle SSH authentication (ssh)

🚀 Example Git Workflow with Linux Commands

mkdir my-project
cd my-project
git inittouch README.md
nano README.mdgit add .
git commit -m "Initial commit"

JavaScript Strings and String Methods: Complete Guide with Examples

Most of what a tester checks is text: page titles, error messages, URLs, table cells, API fields and log lines. JavaScript strings come with dozens of built-in methods to search, cut, clean, change and compare text. In this lesson you will learn how strings work, the methods you will use every day, the difference between similar methods such as slice and substring, and how to clean real UI text before an assertion.

📖 What You’ll Learn: creating strings with quotes and escapes, length and indexing, at(), immutability, searching with includes, startsWith, endsWith and indexOf, extracting with slice and substring, changing case, trim, padStart and padEnd, repeat, replace and replaceAll, split and join, comparing strings with localeCompare, Unicode and emoji length, and cleaning UI text for tests.


🔤 Creating Strings

Definition: a string is a sequence of characters used to represent text. You write string literals with double quotes, single quotes or back-ticks:

📄 create.js

const double = "QA Engineer";
const single = 'Playwright';
const backtick = `Score: ${40 + 2}`;   // template literal, next lesson

console.log(double, "|", single, "|", backtick);
console.log(typeof double, String(123), typeof String(123));

⌨️ Terminal

node create.js

🖥️ Output

QA Engineer | Playwright | Score: 42
string 123 string

Double and single quotes behave the same. Pick one style for your project (Prettier uses double quotes by default). Use the other kind when the text contains a quote, or escape it with a backslash:

📄 escapes.js

console.log("It's ready");
console.log('She said "pass"');
console.log("She said \"pass\"");
console.log("Line 1\nLine 2");      // \n = new line
console.log("Col1\tCol2");          // \t = tab
console.log("C:\\tests\\login.spec.js");   // \\ = one backslash

⌨️ Terminal

node escapes.js

🖥️ Output

It's ready
She said "pass"
She said "pass"
Line 1
Line 2
Col1	Col2
C:\tests\login.spec.js
EscapeMeaning
\nNew line
\tTab
\\Backslash
\" / \'Quote inside a string with the same quotes
\u{1F600}A Unicode character by code point

📏 Length, Indexes and at()

Each character has a position (an index) starting at 0. length is the number of characters.

📄 index.js

const word = "Selenium";

console.log(word.length);
console.log(word[0], word[3], word[word.length - 1]);
console.log(word[20]);            // out of range: undefined
console.log(word.at(0), word.at(-1), word.at(-2));   // at() accepts negative indexes

⌨️ Terminal

node index.js

🖥️ Output

8
S e m
undefined
S m u

💡 Tip: str.at(-1) (ES2022) is the clearest way to read the last character. With bracket notation you need str[str.length - 1].


🔒 Strings Are Immutable

Definition: immutable means a string cannot be changed after it is created. Every string method returns a new string and leaves the original untouched.

📄 immutable.js

let status = "passed";

status.toUpperCase();          // result is thrown away
console.log(status);

status[0] = "P";               // silently ignored
console.log(status);

status = status.toUpperCase(); // store the new string
console.log(status);

⌨️ Terminal

node immutable.js

🖥️ Output

passed
passed
PASSED

⚠️ Watch out: A very common bug is calling a method and not using its result: name.trim(); on its own line does nothing. Write name = name.trim(); or use the result directly.


🔍 Searching: includes, startsWith, endsWith, indexOf

📄 search.js

const url = "https://qa.example.com/checkout?step=2";

console.log(url.includes("checkout"));        // contains?
console.log(url.startsWith("https://"));      // begins with?
console.log(url.endsWith("step=2"));          // ends with?
console.log(url.indexOf("/"), url.lastIndexOf("/"));
console.log(url.indexOf("cart"));             // not found: -1
console.log(url.includes("Checkout"));        // case-sensitive!
console.log(url.toLowerCase().includes("Checkout".toLowerCase()));

⌨️ Terminal

node search.js

🖥️ Output

true
true
true
6 22
-1
false
true
MethodReturns
includes(text)true/false
startsWith(text) / endsWith(text)true/false
indexOf(text) / lastIndexOf(text)Position of the first / last match, or -1
search(regex)Position of the first regex match, or -1

All of these are case-sensitive. Lower-case both sides for a case-insensitive check.


✂️ Extracting: slice and substring

slice(start, end) returns the characters from start up to, but not including, end. Leave out end to go to the end of the string. Negative numbers count from the end.

📄 slice.js

const id = "ORD-2026-000451";

console.log(id.slice(0, 3));     // "ORD"
console.log(id.slice(4, 8));     // "2026"
console.log(id.slice(9));        // from index 9 to the end
console.log(id.slice(-6));       // last 6 characters
console.log(id.slice(-6, -3));

console.log(id.substring(4, 8)); // like slice for positive numbers
console.log(id.substring(8, 4)); // swaps the arguments if start > end
console.log(id.slice(8, 4));     // slice returns ""
console.log(id.substring(-6));   // negative numbers become 0

⌨️ Terminal

node slice.js

🖥️ Output

ORD
2026
000451
000451
000
2026
2026

ORD-2026-000451

💡 Tip: Prefer slice. It supports negative indexes and behaves the same as Array.prototype.slice. The old substr method is deprecated; do not use it in new code.

Combine indexOf and slice to cut text at a marker:

📄 cut.js

const email = "asha.rao@sqatools.in";
const at = email.indexOf("@");
console.log(email.slice(0, at), "|", email.slice(at + 1));

⌨️ Terminal

node cut.js

🖥️ Output

asha.rao | sqatools.in

🧹 Changing Case, Trimming, Padding and Repeating

📄 clean.js

const raw = "   Order CONFIRMED   ";

console.log(JSON.stringify(raw.trim()));
console.log(JSON.stringify(raw.trimStart()), JSON.stringify(raw.trimEnd()));
console.log(raw.trim().toLowerCase(), "|", raw.trim().toUpperCase());

const invoice = "42";
console.log(invoice.padStart(6, "0"));     // "000042"
console.log("Total".padEnd(10, ".") + "₹499");

console.log("=".repeat(20));
console.log("ab".repeat(3));

⌨️ Terminal

node clean.js

🖥️ Output

"Order CONFIRMED"
"Order CONFIRMED   " "   Order CONFIRMED"
order confirmed | ORDER CONFIRMED
000042
Total.....₹499
====================
ababab
  • trim() removes spaces, tabs and line breaks from both ends; text copied from web pages often has them.
  • padStart/padEnd fill a string to a target length, useful for IDs and aligned report columns.
  • toUpperCase/toLowerCase help with case-insensitive comparisons.

🔁 replace and replaceAll

replace(search, replacement) replaces the first match only when search is a string. replaceAll (ES2021) replaces every match.

📄 replace.js

const price = "₹1,29,999";

console.log(price.replace(",", ""));        // only the first comma
console.log(price.replaceAll(",", ""));     // every comma
console.log(price.replace(/[₹,]/g, ""));    // regex with g flag: all matches

const template = "Hello {name}, your order {id} has shipped";
const message = template.replace("{name}", "Asha").replace("{id}", "#451");
console.log(message);

⌨️ Terminal

node replace.js

🖥️ Output

₹129,999
₹129999
129999
Hello Asha, your order #451 has shipped

Regular expressions (lesson 27) make replace far more powerful, for example to remove every non-digit character.


✂️ split and join

split(separator) breaks a string into an array. The array method join(separator) does the reverse.

📄 split-join.js

const csvRow = "asha,tester,Pune,active";
const fields = csvRow.split(",");
console.log(fields, fields.length);

const [name, role] = fields;
console.log(name, role);

console.log("a b  c".split(" "));          // two spaces give an empty item
console.log("a b  c".split(/\s+/));       // regex: any run of whitespace
console.log("QA".split(""));              // into characters
console.log("x,y,z".split(",", 2));        // limit the number of parts

const tags = ["smoke", "login", "p1"];
console.log(tags.join(", "), "|", tags.join("-"));

const slug = "  Learn JavaScript Strings  ".trim().toLowerCase().split(" ").join("-");
console.log(slug);

⌨️ Terminal

node split-join.js

🖥️ Output

[ 'asha', 'tester', 'Pune', 'active' ] 4
asha tester
[ 'a', 'b', '', 'c' ]
[ 'a', 'b', 'c' ]
[ 'Q', 'A' ]
[ 'x', 'y' ]
smoke, login, p1 | smoke-login-p1
learn-javascript-strings

⚖️ Comparing Strings

=== compares exactly, including case and spaces. < and > compare by character codes, so uppercase letters sort before lowercase ones. localeCompare compares the way people expect for a language:

📄 compare.js

console.log("apple" === "Apple");
console.log("Zebra" < "apple");                       // code order: true
console.log("apple".localeCompare("Zebra"));          // negative: apple first

const names = ["ravi", "Asha", "émile", "Bala"];
console.log([...names].sort());                        // code order
console.log([...names].sort((a, b) => a.localeCompare(b)));   // human order

console.log("résumé".localeCompare("RESUME", "en", { sensitivity: "base" }) === 0);

⌨️ Terminal

node compare.js

🖥️ Output

false
true
-1
[ 'Asha', 'Bala', 'ravi', 'émile' ]
[ 'Asha', 'Bala', 'émile', 'ravi' ]
true

💡 Tip: When a test checks that a table column is sorted, build the expected order with localeCompare (or Intl.Collator) in the same locale as the application.


😀 Unicode, Emoji and length

JavaScript strings are made of UTF-16 code units. Most characters use one unit, but many emoji and some rare characters use two, so length can be larger than the number of visible characters:

📄 unicode.js

const text = "QA 👍";
console.log(text.length);                // 5, not 4
console.log([...text].length);           // spread splits by code point: 4
console.log(text.slice(0, 4));           // may cut an emoji in half
console.log([...text].slice(0, 4).join(""));
console.log("👍".codePointAt(0).toString(16));

⌨️ Terminal

node unicode.js

🖥️ Output

5
4
QA �
QA 👍
1f44d

⚠️ Watch out: If a form limits input to “20 characters”, find out whether the application counts code units or visible characters, and test with emoji and accented letters. These are classic boundary-test cases.


🧪 Tester Scenario: Clean and Check UI Text

Text from a web page often contains extra spaces, line breaks and different case. This helper normalises text before comparing, and a second helper extracts values from a summary line:

📄 ui-text.js

function normalise(text) {
  return text.replace(/\s+/g, " ").trim().toLowerCase();
}

function expectTextEquals(actual, expected) {
  const ok = normalise(actual) === normalise(expected);
  console.log(`${ok ? "PASS" : "FAIL"}: "${normalise(actual)}" vs "${normalise(expected)}"`);
  return ok;
}

expectTextEquals("  Welcome back,\n   ASHA!  ", "Welcome back, Asha!");
expectTextEquals("Order #451 shipped", "Order #452 shipped");

const summary = "Showing 1–25 of 1,204 results for \"laptop\"";
const total = Number(summary.slice(summary.indexOf("of ") + 3, summary.indexOf(" results")).replaceAll(",", ""));
const term = summary.slice(summary.indexOf("\"") + 1, summary.lastIndexOf("\""));
console.log({ total, term });

⌨️ Terminal

node ui-text.js

🖥️ Output

PASS: "welcome back, asha!" vs "welcome back, asha!"
FAIL: "order #451 shipped" vs "order #452 shipped"
{ total: 1204, term: 'laptop' }

Playwright’s toHaveText and toContainText already normalise whitespace, but you need helpers like these when you read text with textContent() and process it yourself.


📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Print the first character, the last character and the length of "automation".

Show answer

📄 practice1.js

const word = "automation";
console.log(word[0], word.at(-1), word.length);

🖥️ Output

a n 10

Q2. Write capitalize(str) that makes the first letter uppercase and the rest lowercase: "pLAYWRIGHT" → "Playwright".

Show answer

📄 practice2.js

const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
console.log(capitalize("pLAYWRIGHT"), capitalize("a"), JSON.stringify(capitalize("")));

🖥️ Output

Playwright A ""

Q3. Count how many times the letter "s" appears in "Tests pass successfully" (case-insensitive).

Show answer

📄 practice3.js

const text = "Tests pass successfully";
const count = text.toLowerCase().split("s").length - 1;
console.log(count);

🖥️ Output

7

Splitting on "s" creates one more piece than there are separators.

Q4. Mask a card number so only the last 4 digits show: "4111111111111111" → "************1111".

Show answer

📄 practice4.js

const card = "4111111111111111";
const masked = card.slice(-4).padStart(card.length, "*");
console.log(masked);

🖥️ Output

************1111

Q5. Convert " Login Page Title Test " into a file-name slug "login-page-title-test.spec.js".

Show answer

📄 practice5.js

const name = "  Login Page Title Test  ";
const file = name.trim().toLowerCase().split(/\s+/).join("-") + ".spec.js";
console.log(file);

🖥️ Output

login-page-title-test.spec.js

Q6. Check whether "Was it a car or a cat I saw" is a palindrome, ignoring spaces and case.

Show answer

📄 practice6.js

const text = "Was it a car or a cat I saw";
const clean = text.toLowerCase().replaceAll(" ", "");
const isPalindrome = clean === [...clean].reverse().join("");
console.log(clean, isPalindrome);

🖥️ Output

wasitacaroracatisaw true

🧠 MCQ Quiz: Strings and String Methods

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What is "JavaScript".length?
  2. What does "tester".at(-1) return?
  3. After let s = "abc"; s.toUpperCase(); what is s?
  4. What does "2026-11-23".slice(5, 7) return?
  5. What does "a,b,c".split(",") return?
  6. What does "1,000,000".replace(",", "") return?
  7. Which method checks whether a string begins with “https”?
  8. What does "QA".indexOf("x") return?
  9. What does "7".padStart(3, "0") return?
  10. Why can "👍".length be 2?

💼 Interview Questions and Answers

Q1. What is the difference between slice, substring and substr?

slice(start, end) extracts from start up to (not including) end and supports negative indexes. substring(start, end) is similar but treats negative values as 0 and swaps the arguments if start is larger than end. substr(start, length) takes a length instead of an end index and is deprecated. In modern code use slice.

Q2. Why are strings immutable, and what does that mean for your code?

Immutable means a string value never changes; methods like trim, replace and toUpperCase return new strings. That makes strings safe to share and compare by value, but you must store or use the returned value. Building a long string in a loop creates many intermediate strings; collecting parts in an array and calling join once is often clearer.

Q3. How do you replace all occurrences of a substring?

Use str.replaceAll("old", "new") (ES2021), or str.replace(/old/g, "new") with a global regex, or the older str.split("old").join("new"). Plain replace with a string pattern replaces only the first occurrence.

📄 replace-all.js

const s = "a-b-c";
console.log(s.replaceAll("-", "+"), s.replace(/-/g, "+"), s.split("-").join("+"));

⌨️ Terminal

node replace-all.js

🖥️ Output

a+b+c a+b+c a+b+c

Q4. How would you reverse a string, and what is the catch?

[...str].reverse().join("") spreads the string into code points, reverses the array and joins it. The older str.split("").reverse().join("") breaks emoji and other characters made of two UTF-16 units. Characters built from several code points (for example family emoji or some accented letters) need Intl.Segmenter to be reversed correctly.

Q5. How do you compare UI text robustly in a test?

Normalise both sides first: collapse whitespace (replace(/\s+/g, " ")), trim, and lower-case if case does not matter. Compare with === after normalising, or use matchers that already normalise (toHaveText). Avoid asserting on text that changes (dates, counters) without extracting and checking the dynamic part separately.


❓ Frequently Asked Questions

🤔 How do I check if a string contains a word in JavaScript?

Use str.includes("word"). For a case-insensitive check, lower-case both: str.toLowerCase().includes("word"). For whole-word matches use a regular expression with \b.

🤔 How do I convert a string to an array?

Use str.split(separator) to split on a separator, or [...str] / Array.from(str) to get individual characters.

🤔 What is the difference between single and double quotes?

None in behaviour. Choose one style for consistency and use the other (or escapes) when the text contains a quote. Back-ticks create template literals.

🤔 How do I remove spaces from a string?

Use trim() for the ends, replaceAll(" ", "") for every space, or replace(/\s+/g, "") for all whitespace including tabs and line breaks.


🏁 Summary

  • Strings are immutable sequences of characters; every method returns a new string.
  • Use length, indexes and at() to read characters; includes, startsWith, indexOf to search.
  • Use slice to extract, trim/padStart/toLowerCase to clean, replaceAll to replace.
  • split turns text into arrays and join turns arrays into text.
  • Normalise whitespace and case before comparing UI text, and remember emoji can count as two characters.

Next, continue with Lesson 26: Template Literals. For extra practice, solve the JavaScript string practice programs.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Github Interview Questions And Answers

1. What is GitHub? How is it different from Git?

👉 Answer:

  • Git is a distributed version control system used to track code changes.
  • GitHub is a cloud-based platform that hosts Git repositories and adds collaboration features.

👉 Use Case:
In a team project, developers use Git locally and push code to GitHub for collaboration, reviews, and CI/CD.


2. What is a Repository?

👉 Answer:
A repository (repo) is a storage space for your project that contains code, files, and version history.

👉 Use Case:
You create a repo for a Playwright automation project where all test scripts, configs, and reports are stored.


3. What is the difference between Fork and Clone?

👉 Answer:

  • Fork: Copy of someone else’s repo into your GitHub account.
  • Clone: Copy of a repo to your local machine.

👉 Use Case:

  • Fork: Contributing to open-source.
  • Clone: Working on your team project locally.

4. What is a Branch?

👉 Answer:
A branch is a separate line of development.

👉 Use Case:
You create:

  • main → production code
  • feature/login-test → new feature work

5. What is a Pull Request (PR)?

👉 Answer:
A PR is a request to merge changes from one branch to another.

👉 Use Case:
QA automation engineer raises a PR after adding test cases → Developer reviews → merges into main.


6. What is Merge Conflict?

👉 Answer:
Occurs when Git cannot automatically merge changes.

👉 Use Case:
Two developers modify the same file → conflict → manually resolved before merge.


7. What is GitHub Actions?

👉 Answer:
A CI/CD tool in GitHub used to automate workflows.

👉 Use Case:

  • Run Playwright tests automatically on every PR
  • Deploy app after merge

8. What is .gitignore?

👉 Answer:
A file that specifies which files Git should ignore.

👉 Use Case:
Ignore:

  • node_modules/
  • test-results/
  • .env

9. What is Git Workflow (Branching Strategy)?

👉 Answer:
A process defining how teams use branches.

👉 Common strategies:

  • Git Flow
  • Feature Branch Workflow

👉 Use Case:

  • Create feature branch
  • Push code
  • Raise PR
  • Review → Merge

10. What is Staging in Git?

👉 Answer:
Intermediate area before committing changes.

👉 Commands:

git add .
git commit -m "message"

👉 Use Case:
You selectively add only required files before committing.


11. Difference between Commit and Push?

👉 Answer:

  • Commit: Save changes locally
  • Push: Upload changes to GitHub

👉 Use Case:
You commit multiple times locally → push once after testing.


12. What is Rebase vs Merge?

👉 Answer:

  • Merge: Keeps history (creates merge commit)
  • Rebase: Rewrites history (linear)

👉 Use Case:
Rebase keeps clean commit history before merging feature branch.


13. What is Tag in Git?

👉 Answer:
A tag marks a specific version of code.

👉 Use Case:
Mark releases like:

v1.0
v2.0

14. What is Git Stash?

👉 Answer:
Temporarily saves uncommitted changes.

👉 Use Case:
You are working on a feature but need to switch branches quickly.


15. What is Code Review in GitHub?

👉 Answer:
Process of reviewing code before merging.

👉 Use Case:

  • Developer checks logic
  • QA verifies test coverage
  • Ensures code quality

🔹 Scenario-Based GitHub Interview Questions


16. You pushed wrong code to main branch. What will you do?

👉 Answer:

  • Revert commit:
git revert <commit-id>

OR

  • Reset (if safe):
git reset --hard HEAD~1

👉 Best Practice:
Avoid direct commits to main → use PR workflow.


17. Multiple developers working on same feature. How to manage?

👉 Answer:

  • Use feature branches
  • Regularly pull latest changes
  • Resolve conflicts early

👉 Use Case:
Each dev works on sub-features → merged via PR.


18. How do you handle large files in GitHub?

👉 Answer:
Use Git LFS (Large File Storage).

👉 Use Case:
Store large test data or binaries.


19. How do you secure sensitive data in GitHub?

👉 Answer:

  • Never commit secrets
  • Use GitHub Secrets
  • Use .gitignore

👉 Use Case:
Store API keys in environment variables.


20. Explain CI/CD pipeline using GitHub Actions

👉 Answer:

  1. Code pushed to GitHub
  2. Workflow triggers
  3. Build runs
  4. Tests execute
  5. Deploy

👉 Use Case:
Playwright tests run automatically on every commit.


🔹 Advanced Practical Questions


21. How do you revert a specific file to previous version?

git checkout <commit-id> -- file.js

22. How do you squash commits?

git rebase -i HEAD~3

👉 Combine multiple commits into one.


23. What is Detached HEAD?

👉 Answer:
When you’re not on any branch.

👉 Use Case:
Checking old commit without affecting current branch.


24. How do you delete a branch?

git branch -d branch-name
git push origin --delete branch-name

25. What is Upstream in Git?

👉 Answer:
Reference to original repository (especially in forks).

👉 Use Case:
Keep your fork updated with original repo.


Mock Interview: GitHub (Real Company Style)


🔹 Round 1: Basics + Practical Understanding

❓ Q1: Explain your GitHub workflow in your current project.

👉 Strong Answer:

“We follow a feature branch workflow. Each task starts with a new branch from main. After development, we push code and raise a pull request. CI runs automatically using GitHub Actions. After code review and approvals, we merge into main. Direct commits to main are restricted.”

👉 What interviewer checks:

  • Real experience
  • Collaboration understanding
  • CI/CD awareness

❓ Q2: What happens when you run git push?

👉 Strong Answer:

“It uploads local commits from my machine (using Git) to the remote repository on GitHub, making them available to the team.”

👉 Follow-up trap:
👉 “What if push is rejected?”

✔️ Answer:

“It usually means my branch is behind. I pull the latest changes, resolve conflicts if any, and push again.”


🔹 Round 2: Scenario-Based Questions


❓ Q3: You and another developer changed the same file. Your PR shows conflict. What do you do?

👉 Strong Answer:

“I pull the latest changes from main, resolve conflicts locally, test the code, commit the fix, and push again to update the PR.”

👉 Bonus point:
Mention testing after conflict resolution.


❓ Q4: You accidentally pushed sensitive data (API key) to GitHub. What will you do?

👉 Strong Answer:

“First, I revoke the key immediately. Then I remove it from the repository, rewrite history if needed, and ensure it’s added to .gitignore. Going forward, I store secrets using GitHub Secrets.”

👉 What interviewer checks:

  • Security awareness
  • Real-world handling

❓ Q5: Your teammate’s PR broke the build. What should happen?

👉 Strong Answer:

“The CI pipeline should fail automatically. The PR should not be merged until the issue is fixed. We enforce required checks before merging.”

👉 Extra credit:
Mention branch protection rules.


🔹 Round 3: CI/CD + Automation (Very Important)


❓ Q6: How do you integrate automation tests with GitHub?

👉 Strong Answer:

“We use GitHub Actions to trigger Playwright tests on every PR. The workflow installs dependencies, runs tests, and publishes reports.”

👉 Example flow:

  • PR created
  • Tests run automatically
  • Pass → merge allowed
  • Fail → fix required

❓ Q7: How do you ensure code quality before merging?

👉 Strong Answer:

“We use a combination of:

  • Pull request reviews
  • Automated tests
  • Linting checks
  • CI validation

Only after all checks pass, the PR is merged.”


🔹 Round 4: Advanced Problem Solving


❓ Q8: Your main branch is broken after a merge. What will you do?

👉 Strong Answer:

“I would quickly identify the faulty commit and revert it using git revert. Then fix the issue in a new branch and raise another PR.”

👉 Important:
Avoid rewriting history in shared branches.


❓ Q9: How do you handle multiple environments (dev, staging, prod)?

👉 Strong Answer:

“We use different branches or deployment workflows. For example:

  • develop → dev environment
  • main → production
    CI/CD pipelines deploy automatically based on branch.”

❓ Q10: How do you manage large teams working on the same repo?

👉 Strong Answer:

“We use:

  • Feature branches
  • Clear naming conventions
  • Code owners
  • Mandatory PR reviews
  • CI/CD checks

This ensures smooth collaboration and avoids conflicts.”


🔹 Round 5: Rapid Fire (Quick Checks)


❓ Difference between Fork and Clone?

👉 Fork = copy on GitHub
👉 Clone = copy on local machine


❓ What is HEAD in Git?

👉 Pointer to the current commit/branch


❓ What is Rebase?

👉 Rewrites commit history to make it linear


❓ What is Stash?

👉 Temporarily saves uncommitted changes


❓ What is a Tag?

👉 Marks a release/version


🔹 Real Interview Challenge (Hands-On Thinking)


❓ Q11: Design a GitHub workflow for automation testing.

👉 Strong Answer:

“I would:

  1. Trigger workflow on PR and push
  2. Install dependencies
  3. Run Playwright tests
  4. Generate reports
  5. Upload artifacts
  6. Fail build if tests fail

This ensures only tested code gets merged.”


🔹 Final HR + Practical Question


❓ Q12: Tell me a real problem you faced in GitHub and how you solved it.

👉 Sample Answer:

“We had frequent merge conflicts due to long-running branches. I suggested smaller PRs and frequent rebasing. This reduced conflicts and improved deployment speed.”



Playwright Save Login Session with POM

Here’s a complete, real-world Playwright POM framework showing how to:

  • Login once using beforeAll
  • Share the session across tests
  • Use Page Object Model (POM)
  • Follow best practices for scalability

✅ 1. Project Structure (Recommended)

playwright-project/
│
├── tests/
│ ├── login.setup.ts # Login once & save session
│ ├── example.spec.ts # Actual test cases
│
├── pages/
│ ├── LoginPage.ts
│ ├── DashboardPage.ts
│
├── utils/
│ ├── baseTest.ts # Custom fixture (optional advanced)
│
├── playwright.config.ts
└── package.json

✅ 2. Login Page (POM)

pages/LoginPage.ts

import { Page } from '@playwright/test';export class LoginPage {
readonly page: Page; constructor(page: Page) {
this.page = page;
} async navigate() {
await this.page.goto('https://example.com/login');
} async login(username: string, password: string) {
await this.page.fill('#username', username);
await this.page.fill('#password', password);
await this.page.click('#loginBtn');
}
}

✅ 3. Dashboard Page (POM)

pages/DashboardPage.ts

import { Page, expect } from '@playwright/test';export class DashboardPage {
readonly page: Page; constructor(page: Page) {
this.page = page;
} async verifyDashboardLoaded() {
await expect(this.page.locator('h1')).toHaveText('Dashboard');
}
}

✅ 4. Login Setup (Runs Once Before All Tests)

👉 This is the key part (beforeAll session handling)

tests/login.setup.ts

import { test as setup } from '@playwright/test';
import { LoginPage } from '../pages/LoginPage';setup('Login and save session', async ({ page }) => {
const loginPage = new LoginPage(page); await loginPage.navigate();
await loginPage.login('testuser', 'password123'); // Save session
await page.context().storageState({ path: 'storageState.json' });
});

✅ 5. Playwright Config (Use Stored Session)

playwright.config.ts

import { defineConfig } from '@playwright/test';export default defineConfig({
testDir: './tests', use: {
baseURL: 'https://example.com',
storageState: 'storageState.json', // reuse login session
headless: false
}, projects: [
{
name: 'setup',
testMatch: /login\.setup\.ts/,
},
{
name: 'tests',
dependencies: ['setup'], // ensures login runs first
testMatch: /.*\.spec\.ts/,
},
],
});

✅ 6. Test File (Uses Shared Session)

tests/example.spec.ts

import { test } from '@playwright/test';
import { DashboardPage } from '../pages/DashboardPage';test.describe('Dashboard Tests', () => { test.beforeAll(async () => {
console.log('Runs once before all tests');
}); test('Verify dashboard page', async ({ page }) => {
const dashboard = new DashboardPage(page); await page.goto('/dashboard');
await dashboard.verifyDashboardLoaded();
}); test('Another test using same session', async ({ page }) => {
await page.goto('/dashboard/settings');
console.log('User is already logged in');
});});

✅ 7. How This Works (Important)

🔹 Flow:

  1. login.setup.ts runs first
  2. Logs in and saves session → storageState.json
  3. All test files reuse this session
  4. No repeated login → faster execution

✅ 8. Alternative: Using beforeAll Without storageState (Not Recommended)

test.beforeAll(async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage(); await page.goto('/login');
await page.fill('#username', 'user');
await page.fill('#password', 'pass');
await page.click('#loginBtn'); // ❌ This session is NOT shared across tests automatically
});

👉 Problem:

  • Each test gets a new context
  • Session is NOT reused

✅ 9. Best Practice Summary

✔ Use storageState (Recommended)
✔ Keep login logic in setup file
✔ Use POM for maintainability
✔ Use project dependencies
✔ Avoid login in every test


✅ 10. Pro Tips (Real Project)

  • Store credentials in .env
  • Use multiple storage states for multi-users
  • Use fixtures for advanced reuse
  • Add retry logic for flaky login

Here’s a complete, real-world Playwright setup for multi-user session handling (Admin + User) using POM + storageState + project dependencies.

This is how teams handle role-based testing at scale.


✅ 1. Goal

We want to:

  • Login as Admin
  • Login as Normal User
  • Save both sessions separately
  • Run tests using either role without logging in again

✅ 2. Project Structure

playwright-project/
│
├── tests/
│ ├── setup/
│ │ ├── admin.setup.ts
│ │ ├── user.setup.ts
│ │
│ ├── admin.spec.ts
│ ├── user.spec.ts
│
├── pages/
│ ├── LoginPage.ts
│ ├── DashboardPage.ts
│
├── storage/
│ ├── adminState.json
│ ├── userState.json
│
├── playwright.config.ts

✅ 3. Login Page (Reusable POM)

pages/LoginPage.ts

import { Page } from '@playwright/test';export class LoginPage {
constructor(private page: Page) {} async navigate() {
await this.page.goto('/login');
} async login(username: string, password: string) {
await this.page.fill('#username', username);
await this.page.fill('#password', password);
await this.page.click('#loginBtn');
}
}

✅ 4. Admin Login Setup

tests/setup/admin.setup.ts

import { test as setup } from '@playwright/test';
import { LoginPage } from '../../pages/LoginPage';setup('Login as Admin', async ({ page }) => {
const login = new LoginPage(page); await login.navigate();
await login.login('adminUser', 'adminPass'); await page.context().storageState({
path: 'storage/adminState.json',
});
});

✅ 5. User Login Setup

tests/setup/user.setup.ts

import { test as setup } from '@playwright/test';
import { LoginPage } from '../../pages/LoginPage';setup('Login as User', async ({ page }) => {
const login = new LoginPage(page); await login.navigate();
await login.login('normalUser', 'userPass'); await page.context().storageState({
path: 'storage/userState.json',
});
});

✅ 6. Playwright Config (Multi-User Projects)

playwright.config.ts

import { defineConfig } from '@playwright/test';export default defineConfig({
testDir: './tests', use: {
baseURL: 'https://example.com',
headless: false,
}, projects: [
// 🔹 Admin Setup
{
name: 'admin-setup',
testMatch: /admin\.setup\.ts/,
}, // 🔹 User Setup
{
name: 'user-setup',
testMatch: /user\.setup\.ts/,
}, // 🔹 Admin Tests
{
name: 'admin-tests',
dependencies: ['admin-setup'],
use: {
storageState: 'storage/adminState.json',
},
testMatch: /admin\.spec\.ts/,
}, // 🔹 User Tests
{
name: 'user-tests',
dependencies: ['user-setup'],
use: {
storageState: 'storage/userState.json',
},
testMatch: /user\.spec\.ts/,
},
],
});

✅ 7. Admin Test Example

tests/admin.spec.ts

import { test, expect } from '@playwright/test';test('Admin can access admin panel', async ({ page }) => {
await page.goto('/admin'); await expect(page.locator('h1')).toHaveText('Admin Dashboard');
});

✅ 8. User Test Example

tests/user.spec.ts

import { test, expect } from '@playwright/test';test('User cannot access admin panel', async ({ page }) => {
await page.goto('/admin'); await expect(page.locator('text=Access Denied')).toBeVisible();
});

✅ 9. Advanced: Use Fixtures (Cleaner Approach)

👉 Create a reusable fixture for roles

utils/fixtures.ts

import { test as base } from '@playwright/test';export const test = base.extend<{
adminPage: any;
userPage: any;
}>({
adminPage: async ({ browser }, use) => {
const context = await browser.newContext({
storageState: 'storage/adminState.json',
});
const page = await context.newPage();
await use(page);
await context.close();
}, userPage: async ({ browser }, use) => {
const context = await browser.newContext({
storageState: 'storage/userState.json',
});
const page = await context.newPage();
await use(page);
await context.close();
},
});

Use Fixture in Test

import { test } from '../utils/fixtures';test('Admin vs User behavior', async ({ adminPage, userPage }) => {
await adminPage.goto('/dashboard');
await userPage.goto('/dashboard'); console.log('Both sessions running in parallel');
});

✅ 10. Key Benefits

✔ No repeated login
✔ Faster test execution
✔ Role-based validation
✔ Parallel execution ready
✔ Clean separation of concerns


🚀 Real-World Use Cases

  • Admin vs Customer flows
  • RBAC (Role-Based Access Control) testing
  • Multi-tenant apps
  • Permission validation

⚠️ Common Mistakes

❌ Using same storageState for all users
❌ Logging in inside every test
❌ Hardcoding credentials
❌ Not using project dependencies


✅ Pro Tips

  • Use .env for credentials
  • Add API login for speed
  • Rotate test users (avoid blocking)
  • Keep session fresh (auto re-login if expired)

JavaScript Functions: Declaration, Parameters, Return and Expressions

A function is a reusable block of code with a name. Instead of copying the same login steps, price calculation or date formatting into ten places, you write it once as a function and call it wherever you need it. Every Playwright test is itself a function, and every page object is built from functions. In this lesson you will learn how to declare and call functions, pass data in with parameters, send results back with return, and write small, pure helpers that are easy to test.

📖 What You’ll Learn: what a function is, function declarations, calling functions, parameters versus arguments, return values and early return, functions that return undefined, function expressions, hoisting differences, functions as values, naming and documenting functions, pure functions versus side effects, and writing reusable test helpers.


🧩 What Is a Function?

Definition: a function is a named, reusable block of code that performs a task. It can receive input values (parameters) and send back a result (a return value). Defining a function does not run it; calling it does.

📄 function.js

// 1. Define (declare) the function
function greet(name) {
  return `Hello, ${name}!`;
}

// 2. Call it as many times as you like
console.log(greet("Asha"));
console.log(greet("Ravi"));

const message = greet("QA team");   // store the returned value
console.log(message.length);

⌨️ Terminal

node function.js

🖥️ Output

Hello, Asha!
Hello, Ravi!
15
  • function is the keyword, greet is the name, name is a parameter.
  • greet("Asha") calls the function with the argument "Asha".
  • return sends a value back to the caller, where you can print it, store it or pass it on.

Functions give you three benefits: reuse (write once, call many times), readability (a good name explains the code) and testability (a small function can be checked on its own).


📥 Parameters vs Arguments

Parameters are the names listed in the function definition. Arguments are the actual values you pass when you call it. Arguments are matched to parameters by position.

📄 params.js

function orderSummary(item, qty, price) {   // item, qty, price are parameters
  return `${qty} x ${item} = ${(qty * price).toFixed(2)}`;
}

console.log(orderSummary("Pen", 3, 10));   // "Pen", 3, 10 are arguments

// Missing arguments are undefined; extra arguments are ignored
console.log(orderSummary("Pen", 3));
console.log(orderSummary("Pen", 3, 10, "ignored"));

⌨️ Terminal

node params.js

🖥️ Output

3 x Pen = 30.00
3 x Pen = NaN
3 x Pen = 30.00

⚠️ Watch out: JavaScript does not check how many arguments you pass. A missing argument silently becomes undefined, which turns arithmetic into NaN. The next lessons show default parameters and validation to protect against this.

Functions receive copies of primitive values but references to objects. Changing an object parameter changes the caller’s object too:

📄 by-reference.js

function addTag(test, tag) {
  test.tags.push(tag);      // changes the caller's object
  tag = "changed";          // only changes the local copy
}

const test = { name: "login", tags: ["smoke"] };
const newTag = "regression";
addTag(test, newTag);
console.log(test.tags, newTag);

⌨️ Terminal

node by-reference.js

🖥️ Output

[ 'smoke', 'regression' ] regression

📤 Return Values

return ends the function immediately and sends a value back. A function without return (or with an empty return;) returns undefined.

📄 return.js

function add(a, b) {
  return a + b;
  console.log("never runs");   // code after return is unreachable
}

function logOnly(a, b) {
  console.log("sum is", a + b);   // prints, but returns nothing
}

console.log(add(2, 3));
const result = logOnly(2, 3);
console.log("logOnly returned:", result);

⌨️ Terminal

node return.js

🖥️ Output

5
sum is 5
logOnly returned: undefined

A function can return any value: a number, a string, an object, an array, even another function. Use an object to return several values at once:

📄 return-object.js

function analyse(times) {
  const total = times.reduce((sum, t) => sum + t, 0);
  return {
    count: times.length,
    average: total / times.length,
    slowest: Math.max(...times),
  };
}

const stats = analyse([320, 410, 1290, 250]);
console.log(stats);
console.log(`Slowest response: ${stats.slowest} ms`);

⌨️ Terminal

node return-object.js

🖥️ Output

{ count: 4, average: 567.5, slowest: 1290 }
Slowest response: 1290 ms

Early return

A return inside an if stops the function early. This is the guard-clause pattern from the if/else lesson:

📄 early-return.js

function discountFor(total) {
  if (total <= 0) return 0;
  if (total >= 5000) return total * 0.1;
  if (total >= 1000) return total * 0.05;
  return 0;
}

for (const t of [-5, 500, 1200, 8000]) {
  console.log(t, "->", discountFor(t));
}

⌨️ Terminal

node early-return.js

🖥️ Output

-5 -> 0
500 -> 0
1200 -> 60
8000 -> 800

📝 Function Expressions

Definition: a function expression creates a function as part of an expression, usually by assigning it to a variable. The function itself can be anonymous (have no name).

📄 expression.js

// Function declaration
function square(n) {
  return n * n;
}

// Function expression stored in a constant
const cube = function (n) {
  return n * n * n;
};

// Arrow function expression (next lesson)
const double = (n) => n * 2;

console.log(square(4), cube(3), double(5));
console.log(typeof cube);

⌨️ Terminal

node expression.js

🖥️ Output

16 27 10
function

The difference: hoisting

Function declarations are hoisted with their body, so you can call them before the line where they are written. Function expressions follow the rules of the variable that holds them, so calling them early fails:

📄 hoisting.js

console.log(declared(2));     // works: declarations are hoisted

function declared(n) {
  return n + 1;
}

console.log(expressed(2));    // fails: the const is in the temporal dead zone

const expressed = function (n) {
  return n + 1;
};

⌨️ Terminal

node hoisting.js

🖥️ Output

3
/home/you/js-course/hoisting.js:7
console.log(expressed(2));    // fails: the const is in the temporal dead zone
            ^

ReferenceError: Cannot access 'expressed' before initialization
    at Object.<anonymous> (/home/you/js-course/hoisting.js:7:13)

Node.js v26.13.0
DeclarationExpression
Syntaxfunction name() {}const name = function () {};
Hoisted with bodyYesNo
Can be anonymousNoYes
Typical useTop-level helpersCallbacks, values stored in objects

🎁 Functions Are Values

In JavaScript, functions are first-class values: you can store them in variables, put them in objects and arrays, pass them to other functions and return them from functions.

📄 values.js

const checks = {
  isPositive: function (n) { return n > 0; },
  isEven: (n) => n % 2 === 0,
};

console.log(checks.isPositive(5), checks.isEven(5));

const steps = [
  () => console.log("open page"),
  () => console.log("fill form"),
  () => console.log("submit"),
];
for (const step of steps) step();

function runTwice(action) {      // a function as an argument
  action();
  action();
}
runTwice(() => console.log("ping"));

⌨️ Terminal

node values.js

🖥️ Output

true false
open page
fill form
submit
ping
ping

Passing functions to other functions is the foundation of callbacks, array methods like map and filter, and every Playwright test('name', async () => {...}) call. The Higher-Order Functions lesson covers it in depth.


✨ Pure Functions vs Side Effects

Definition: a pure function always returns the same output for the same input and changes nothing outside itself. A function with side effects changes something else: a global variable, an object argument, a file, the page, or the console.

📄 pure.js

let runCount = 0;

// Impure: depends on and changes outside state
function nextRunName() {
  runCount++;
  return `run-${runCount}`;
}

// Pure: depends only on its inputs
function runName(n) {
  return `run-${n}`;
}

console.log(nextRunName(), nextRunName());   // different results each call
console.log(runName(1), runName(1));         // always the same

⌨️ Terminal

node pure.js

🖥️ Output

run-1 run-2
run-1 run-1

💡 Tip: Keep calculations (formatting, parsing, validation) in pure functions, and keep side effects (clicking, writing files, calling APIs) in a few clearly named functions. Pure functions are trivial to unit test.


🏷️ Naming and Documenting Functions

  • Start with a verb that says what the function does: calculateTotal, getUser, isValidEmail, formatDate.
  • Use is/has/can for functions that return a boolean.
  • Keep functions small and focused on one job. If you need “and” to describe it, split it.
  • Prefer at most three parameters; for more, pass one options object (covered in the Parameters lesson).

Document public helpers with JSDoc so editors show hints and catch mistakes:

📄 jsdoc.js

/**
 * Formats an amount as Indian rupees.
 * @param {number} amount - The amount in rupees
 * @returns {string} The formatted price, for example "₹1,299.50"
 */
function formatINR(amount) {
  return new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" }).format(amount);
}

console.log(formatINR(1299.5));

⌨️ Terminal

node jsdoc.js

🖥️ Output

₹1,299.50

🧪 Tester Scenario: Reusable Test-Data Helpers

Test suites share many small tasks: building users, generating unique emails, checking responses. Putting them into functions keeps every test short and consistent:

📄 helpers.js

function uniqueEmail(prefix = "qa") {
  return `${prefix}+${Date.now()}@sqatools.in`;
}

function buildUser(overrides) {
  return {
    name: "Test User",
    email: uniqueEmail(),
    role: "tester",
    active: true,
    ...overrides,               // override only what a test cares about
  };
}

function expectStatus(response, expected) {
  if (response.status !== expected) {
    throw new Error(`Expected status ${expected} but got ${response.status}`);
  }
  return true;
}

const admin = buildUser({ role: "admin" });
const disabled = buildUser({ active: false, name: "Old Account" });
console.log(admin.role, admin.active, /^qa\+\d+@sqatools\.in$/.test(admin.email));
console.log(disabled.name, disabled.active);

console.log(expectStatus({ status: 201 }, 201));
try {
  expectStatus({ status: 500 }, 201);
} catch (e) {
  console.log(e.message);
}

⌨️ Terminal

node helpers.js

🖥️ Output

admin true true
Old Account false
true
Expected status 201 but got 500
  • prefix = "qa" is a default parameter, used when no argument is passed.
  • ...overrides copies the properties passed in over the defaults (spread syntax, covered in Module 6).
  • expectStatus throws an error with a clear message, which is how assertions fail a test.

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Write celsiusToFahrenheit(c) that returns c * 9 / 5 + 32, and print the results for 0, 37 and 100.

Show answer

📄 practice1.js

function celsiusToFahrenheit(c) {
  return (c * 9) / 5 + 32;
}

for (const c of [0, 37, 100]) {
  console.log(`${c}°C = ${celsiusToFahrenheit(c)}°F`);
}

🖥️ Output

0°C = 32°F
37°C = 98.6°F
100°C = 212°F

Q2. Write isEven(n) that returns a boolean, then use it to print the even numbers in [3, 8, 11, 14, 20].

Show answer

📄 practice2.js

function isEven(n) {
  return n % 2 === 0;
}

for (const n of [3, 8, 11, 14, 20]) {
  if (isEven(n)) console.log(n);
}

🖥️ Output

8
14
20

Q3. What does this print, and why?

function total(a, b) {
  a + b;
}
console.log(total(2, 3));
Show answer

📄 practice3.js

function total(a, b) {
  a + b;
}
console.log(total(2, 3));

🖥️ Output

undefined

The function calculates a + b but never returns it, so it returns undefined. Write return a + b;.

Q4. Write minMax(numbers) that returns an object with the smallest and largest number of an array.

Show answer

📄 practice4.js

function minMax(numbers) {
  return { min: Math.min(...numbers), max: Math.max(...numbers) };
}

console.log(minMax([42, 7, 19, 88, 3]));

🖥️ Output

{ min: 3, max: 88 }

Q5. Write passRate(passed, total) that returns the pass percentage rounded to one decimal, and returns 0 when total is 0 (no division by zero).

Show answer

📄 practice5.js

function passRate(passed, total) {
  if (total === 0) return 0;
  return Math.round((passed / total) * 1000) / 10;
}

console.log(passRate(17, 20), passRate(2, 3), passRate(0, 0));

🖥️ Output

85 66.7 0

Q6. Make this function pure: it should not change the array it receives.

function addItem(cart, item) {
  cart.push(item);
  return cart;
}
Show answer

📄 practice6.js

function addItem(cart, item) {
  return [...cart, item];   // new array; the original is untouched
}

const cart = ["pen"];
const updated = addItem(cart, "book");
console.log(cart, updated);

🖥️ Output

[ 'pen' ] [ 'pen', 'book' ]

🧠 MCQ Quiz: Functions

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What does a function return if it has no return statement?
  2. In function add(a, b) {} and add(2, 3), what are 2 and 3?
  3. What is the value of a parameter when no argument is passed?
  4. Which can be called before the line where it is defined?
  5. What happens to code after a return statement in the same block?
  6. Which describes a pure function?
  7. What is the result?
    function f(obj) { obj.n = 2; }
    const o = { n: 1 };
    f(o);
    console.log(o.n);
  8. How can a function return two values?
  9. Which name best follows conventions for a function that checks a login state?
  10. What does typeof function () {} return?

💼 Interview Questions and Answers

Q1. What is the difference between a function declaration and a function expression?

A declaration (function name() {}) is a statement that creates a named binding hoisted with its body, so it can be called anywhere in its scope. An expression (const name = function () {} or an arrow function) creates the function as a value when that line runs; it follows the hoisting rules of the variable (TDZ for let/const) and can be anonymous. Expressions are used for callbacks and conditional definitions.

Q2. Are arguments passed by value or by reference in JavaScript?

Always by value, but for objects the value is a reference. Reassigning the parameter inside the function does not affect the caller, while mutating the object it points to does. That is why helpers that modify shared test data can cause flaky tests, and why pure functions return new objects instead.

Q3. What are first-class functions?

A language has first-class functions when functions are values like any other: they can be assigned to variables, stored in data structures, passed as arguments and returned from other functions. JavaScript supports all of this, which enables callbacks, higher-order functions such as map, closures and the test(name, fn) style of test frameworks.

Q4. Why are small pure functions valuable in test automation?

They are deterministic, so their results can be checked with simple unit tests and they never cause flakiness. They can be reused across UI and API tests (formatting prices, parsing tables, building payloads) and composed into larger helpers. Keeping side effects in a few places (page objects, API clients) makes failures easier to locate.

Q5. What does this code print?

📄 interview.js

function f() {
  return
  { ok: true };
}
console.log(f());
console.log(typeof f, f.length, f.name);

⌨️ Terminal

node interview.js

🖥️ Output

undefined
function 0 f

Automatic semicolon insertion ends the return at the line break, so f() returns undefined. f.length is the number of declared parameters (0) and f.name is the function’s name.


❓ Frequently Asked Questions

🤔 What are the types of functions in JavaScript?

Function declarations, function expressions, arrow functions, methods (functions stored in objects), constructor functions and classes, async functions and generator functions. This module covers the first three in detail.

🤔 Can a JavaScript function return multiple values?

Not directly, but it can return an array or object containing several values, which the caller can unpack with destructuring: const { min, max } = minMax(list);.

🤔 What is the difference between a function and a method?

A method is a function stored as a property of an object and usually called on that object, for example "text".toUpperCase() or page.click().

🤔 How many parameters should a function have?

Ideally three or fewer. For more, pass a single options object such as createUser({ name, role, active }), which also makes calls self-documenting.


🏁 Summary

  • A function is reusable code: declare it once, call it many times; it runs only when called.
  • Parameters are names in the definition; arguments are the values passed; missing arguments are undefined.
  • return sends a value back and ends the function; without it the result is undefined.
  • Function declarations are hoisted with their body; function expressions are not.
  • Functions are values; keep calculations pure and side effects in clearly named helpers.

Next, continue with Lesson 18: Arrow Functions. For extra practice, solve the JavaScript function practice programs.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in