Playwright Custom Fixtures with Examples

In Playwright, fixtures are reusable setup and teardown utilities that help you share test data, page objects, authentication, API clients, and configurations across tests.

Custom fixtures make your framework:

  • Reusable
  • Maintainable
  • Scalable
  • Cleaner and easier to read

1. What is a Fixture in Playwright?

A fixture is a setup environment provided to your test before execution.

Playwright already provides built-in fixtures such as:

  • page
  • browser
  • context
  • request

Example:

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

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

Here, page is a built-in fixture.


2. Why Use Custom Fixtures?

Custom fixtures help when you want to:

  • Reuse login steps
  • Share page objects
  • Create API clients
  • Initialize test data
  • Setup database connections
  • Handle authentication
  • Avoid duplicate code

3. Basic Structure of Custom Fixture

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

export const test = base.extend({

myFixture: async ({}, use) => {

// Setup
const data = "Hello Fixture";

// Provide fixture
await use(data);

// Teardown
console.log("Fixture cleanup");
}
});

4. Example 1 — Simple Custom Fixture

Folder Structure

project
├── tests
│ └── example.spec.ts
│
├── fixtures
│ └── testFixture.ts

Step 1: Create Fixture File

fixtures/testFixture.ts

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

type MyFixtures = {
userName: string;
};

export const test = base.extend<MyFixtures>({

userName: async ({}, use) => {

const name = 'Deepesh';

await use(name);

console.log('Test completed');
}
});

export { expect } from '@playwright/test';

Step 2: Use Fixture in Test

tests/example.spec.ts

import { test, expect } from '../fixtures/testFixture';

test('Custom Fixture Example', async ({ userName }) => {

console.log(userName);

expect(userName).toBe('Deepesh');
});

5. Example 2 — Page Object Fixture

This is the most common real-world usage.


Folder Structure

project
├── pages
│ └── LoginPage.ts
│
├── fixtures
│ └── pageFixture.ts
│
├── tests
│ └── login.spec.ts

Step 1: Create Page Object

pages/LoginPage.ts

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

export class LoginPage {

constructor(private 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');
}
}

Step 2: Create Fixture

fixtures/pageFixture.ts

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

type PageFixtures = {
loginPage: LoginPage;
};

export const test = base.extend<PageFixtures>({

loginPage: async ({ page }, use) => {

const loginPage = new LoginPage(page);

await use(loginPage);
}
});

export { expect } from '@playwright/test';

Step 3: Use Fixture in Test

tests/login.spec.ts

import { test, expect } from '../fixtures/pageFixture';

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

await loginPage.navigate();

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

6. Example 3 — Authentication Fixture

This is extremely useful in enterprise frameworks.


Authentication Fixture

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

type AuthFixtures = {
authenticatedPage: any;
};

export const test = base.extend<AuthFixtures>({

authenticatedPage: async ({ page }, use) => {

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

await page.fill('#username', 'admin');
await page.fill('#password', 'admin123');

await page.click('#login');

// Reuse logged-in page
await use(page);

// Optional cleanup
await page.close();
}
});

export { expect } from '@playwright/test';

Test File

import { test, expect } from '../fixtures/authFixture';

test('Dashboard Test', async ({ authenticatedPage }) => {

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

await expect(
authenticatedPage.locator('h1')
).toContainText('Dashboard');
});

7. Example 4 — API Fixture

Useful for API automation frameworks.


fixtures/apiFixture.ts

import { test as base, request } from '@playwright/test';

type ApiFixture = {
apiContext: any;
};

export const test = base.extend<ApiFixture>({

apiContext: async ({}, use) => {

const apiContext = await request.newContext({

baseURL: 'https://reqres.in/api',

extraHTTPHeaders: {
'Accept': 'application/json'
}
});

await use(apiContext);

await apiContext.dispose();
}
});

export { expect } from '@playwright/test';

API Test

import { test, expect } from '../fixtures/apiFixture';

test('Get Users API', async ({ apiContext }) => {

const response = await apiContext.get('/users?page=2');

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

const body = await response.json();

console.log(body);
});

8. Worker Fixture vs Test Fixture

Playwright supports two fixture scopes.

Fixture TypeScopeRuns
Test FixturePer TestEvery test
Worker FixturePer WorkerOnce per worker

Example of Worker Fixture

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

type WorkerFixture = {
token: string;
};

export const test = base.extend<{}, WorkerFixture>({

token: [async ({}, use) => {

console.log('Generate Token');

const token = 'ABC123TOKEN';

await use(token);

}, { scope: 'worker' }]
});

9. Auto Fixtures

Auto fixtures execute automatically before every test.


Example

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

export const test = base.extend({

autoLogger: [async ({}, use) => {

console.log('Before Test');

await use();

console.log('After Test');

}, { auto: true }]
});

10. Best Practices

Use Fixtures For

  • Login handling
  • API clients
  • Database setup
  • Page objects
  • Environment setup
  • Test data generation

Avoid

  • Very large fixtures
  • Too much business logic
  • Circular dependencies
  • Hardcoded credentials

11. Real Enterprise Framework Structure

project
├── fixtures
│ ├── authFixture.ts
│ ├── apiFixture.ts
│ ├── pageFixture.ts
│
├── pages
│ ├── LoginPage.ts
│ ├── DashboardPage.ts
│
├── tests
│ ├── ui
│ ├── api
│
├── utils
├── test-data
├── playwright.config.ts

12. Advantages of Custom Fixtures

BenefitDescription
ReusabilityAvoid duplicate code
ScalabilityEasier framework growth
MaintainabilityCentralized setup
Clean TestsBetter readability
Faster DevelopmentReuse common logic

13. Interview Questions

Q1. What is a fixture in Playwright?

A reusable setup/teardown utility used in tests.


Q2. Difference between built-in and custom fixtures?

  • Built-in fixtures are provided by Playwright.
  • Custom fixtures are user-defined.

Q3. What is worker scope?

Fixture executes once per worker process.


Q4. Why use fixtures with Page Object Model?

To inject reusable page object instances into tests.


14. Recommended Real-World Usage

Most companies use fixtures for:

  • Authentication
  • Page Object initialization
  • API clients
  • Environment configuration
  • Test reporting
  • Database utilities
  • Logging

15. Summary

Custom fixtures are one of the most important concepts in Playwright frameworks because they:

  • Reduce code duplication
  • Improve maintainability
  • Support scalable automation frameworks
  • Work perfectly with POM and API automation

Most enterprise Playwright frameworks heavily depend on custom fixtures.

Playwright Framework Read Data from a JSON File

Using JSON files in a Playwright framework is a common way to manage:

  • Test data
  • Environment configuration
  • User credentials
  • API payloads
  • Multiple datasets for data-driven testing

1. Project Structure Example

playwright-framework/
│
├── test-data/
│ ├── users.json
│ └── loginData.json
│
├── tests/
│ └── login.spec.ts
│
├── utils/
│ └── jsonReader.ts
│
├── playwright.config.ts
├── package.json
└── tsconfig.json

2. Create a JSON File

test-data/loginData.json

{
"validUser": {
"username": "admin",
"password": "admin123"
},
"invalidUser": {
"username": "wronguser",
"password": "wrongpass"
}
}

3. Read JSON Directly in Playwright Test

tests/login.spec.ts

import { test, expect } from '@playwright/test';
import loginData from '../test-data/loginData.json';

test('Login with valid user', async ({ page }) => {

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

await page.fill('#username', loginData.validUser.username);

await page.fill('#password', loginData.validUser.password);

await page.click('#loginBtn');

await expect(page).toHaveURL(/dashboard/);
});

4. Enable JSON Imports in TypeScript

Update your tsconfig.json.

tsconfig.json

{
"compilerOptions": {
"resolveJsonModule": true,
"esModuleInterop": true
}
}

5. Reading JSON Using fs Module (Dynamic Read)

This approach is useful when:

  • File changes frequently
  • Large datasets
  • Runtime data loading
  • External config management

utils/jsonReader.ts

import fs from 'fs';

export function readJsonFile(path: string) {

const data = fs.readFileSync(path, 'utf-8');

return JSON.parse(data);
}

Usage in Test

import { test, expect } from '@playwright/test';
import { readJsonFile } from '../utils/jsonReader';

test('Login using JSON data', async ({ page }) => {

const testData = readJsonFile('./test-data/loginData.json');

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

await page.fill('#username', testData.validUser.username);

await page.fill('#password', testData.validUser.password);

await page.click('#loginBtn');

await expect(page).toHaveURL(/dashboard/);
});

6. Data-Driven Testing Using JSON

test-data/users.json

[
{
"username": "user1",
"password": "pass1"
},
{
"username": "user2",
"password": "pass2"
},
{
"username": "user3",
"password": "pass3"
}
]

Data-Driven Playwright Test

import { test } from '@playwright/test';
import users from '../test-data/users.json';

users.forEach((user) => {

test(`Login test for ${user.username}`, async ({ page }) => {

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

await page.fill('#username', user.username);

await page.fill('#password', user.password);

await page.click('#loginBtn');
});
});

7. Best Practice in Enterprise Playwright Framework

Keep Separate JSON Files For

PurposeExample File
Login DataloginData.json
API Payloadspayloads.json
Environment Dataenv.json
Test Usersusers.json
Configurationsconfig.json

8. Recommended Folder Structure

test-data/
│
├── ui/
│ ├── login.json
│ └── checkout.json
│
├── api/
│ ├── createUser.json
│ └── updateUser.json
│
└── environments/
├── qa.json
└── prod.json

9. Example: Environment Configuration

environments/qa.json

{
"baseURL": "https://qa.example.com",
"username": "qauser",
"password": "qapass"
}

Usage

import env from '../test-data/environments/qa.json';

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

await page.goto(env.baseURL);
});

10. Async JSON Read Example

import fs from 'fs/promises';

export async function readJson(path: string) {

const data = await fs.readFile(path, 'utf-8');

return JSON.parse(data);
}

11. Real-World Enterprise Utility Class

utils/dataManager.ts

import fs from 'fs';

export class DataManager {

static getTestData(filePath: string) {

const data = fs.readFileSync(filePath, 'utf-8');

return JSON.parse(data);
}
}

Usage

import { test } from '@playwright/test';
import { DataManager } from '../utils/dataManager';

test('Enterprise JSON Example', async ({ page }) => {

const data = DataManager.getTestData(
'./test-data/loginData.json'
);

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

console.log(data.validUser.username);
});

12. Common Errors and Fixes

ErrorSolution
Cannot find JSON moduleAdd resolveJsonModule: true
Unexpected token JSONUse JSON.parse() properly
Path not foundUse correct relative path
Undefined valuesVerify JSON structure

13. Recommended Best Practices

Use JSON When

✅ Static test data
✅ Small-medium datasets
✅ Config management
✅ API request payloads

Playwright API Automation with POM

API Automation with Page Object Model (POM)

What is API Automation in Playwright?

Playwright is not only used for UI automation; it also supports powerful API testing using built-in HTTP request methods.

API automation helps to:

  • Validate backend services
  • Test REST APIs
  • Verify response data
  • Perform authentication testing
  • Integrate API + UI workflows

Why Use Page Object Model (POM) for API Testing?

Page Object Model is a design pattern used to:

  • Separate API logic from test logic
  • Improve code reusability
  • Make framework scalable
  • Reduce code duplication
  • Improve maintenance

Recommended Project Structure

playwright-api-framework/
│
├── tests/
│ ├── user.spec.ts
│ └── booking.spec.ts
│
├── api/
│ ├── UserAPI.ts
│ └── BookingAPI.ts
│
├── utils/
│ ├── apiClient.ts
│ └── testData.ts
│
├── fixtures/
│ └── auth.json
│
├── playwright.config.ts
├── package.json
└── tsconfig.json

Step 1: Install Playwright

Initialize Project

npm init -y

Install Playwright

npm init playwright@latest

Choose:

  • TypeScript
  • VS Code
  • GitHub Actions (optional)

Step 2: Configure Playwright

playwright.config.ts

import { defineConfig } from '@playwright/test';

export default defineConfig({
use: {
baseURL: 'https://reqres.in/api',
extraHTTPHeaders: {
'Content-Type': 'application/json'
}
}
});

Step 3: Create Base API Client

utils/apiClient.ts

This class handles common API operations.

import { APIRequestContext, request } from '@playwright/test';

export class APIClient {
private apiContext!: APIRequestContext;

async createContext() {
this.apiContext = await request.newContext({
baseURL: 'https://reqres.in/api',
extraHTTPHeaders: {
'Content-Type': 'application/json'
}
});
}

getContext() {
return this.apiContext;
}
}

Step 4: Create API Page Object

api/UserAPI.ts

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

export class UserAPI {
readonly request: APIRequestContext;

constructor(request: APIRequestContext) {
this.request = request;
}

async getUsers(pageNumber: number) {
const response = await this.request.get(`/users?page=${pageNumber}`);

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

return await response.json();
}

async createUser(name: string, job: string) {
const response = await this.request.post('/users', {
data: {
name,
job
}
});

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

return await response.json();
}

async updateUser(id: number, name: string, job: string) {
const response = await this.request.put(`/users/${id}`, {
data: {
name,
job
}
});

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

return await response.json();
}

async deleteUser(id: number) {
const response = await this.request.delete(`/users/${id}`);

expect(response.status()).toBe(204);
}
}

Step 5: Write API Test Cases

tests/user.spec.ts

import { test, request, expect } from '@playwright/test';
import { UserAPI } from '../api/UserAPI';

test.describe('User API Tests', () => {

let userAPI: UserAPI;

test.beforeEach(async () => {
const apiContext = await request.newContext({
baseURL: 'https://reqres.in/api'
});

userAPI = new UserAPI(apiContext);
});

test('Get Users List', async () => {

const response = await userAPI.getUsers(2);

expect(response.page).toBe(2);
expect(response.data.length).toBeGreaterThan(0);
});

test('Create New User', async () => {

const response = await userAPI.createUser(
'Deepesh',
'QA Engineer'
);

expect(response.name).toBe('Deepesh');
expect(response.job).toBe('QA Engineer');
});

test('Update Existing User', async () => {

const response = await userAPI.updateUser(
2,
'Deepesh Updated',
'Senior QA'
);

expect(response.name).toBe('Deepesh Updated');
});

test('Delete User', async () => {

await userAPI.deleteUser(2);
});

});

Step 6: Execute Tests

Run All Tests

npx playwright test

Run Specific File

npx playwright test tests/user.spec.ts

Run in Headed Mode

npx playwright test --headed

Generate HTML Report

npx playwright show-report

API Assertions Examples

Validate Status Code

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

Validate Response Body

expect(responseBody.name).toBe('Deepesh');

Validate Headers

expect(response.headers()['content-type'])
.toContain('application/json');

Authentication Example

Login API

async login(email: string, password: string) {

const response = await this.request.post('/login', {
data: {
email,
password
}
});

return await response.json();
}

Token Handling Example

const token = loginResponse.token;

const apiContext = await request.newContext({
extraHTTPHeaders: {
Authorization: `Bearer ${token}`
}
});

Reusable Test Data

utils/testData.ts

export const users = {
adminUser: {
name: 'Deepesh',
job: 'Automation Engineer'
}
};

Advanced Framework Enhancements

You can extend this framework with:

FeaturePurpose
Environment ConfigDEV/UAT/PROD support
LoggerAPI request-response logs
Allure ReportsAdvanced reporting
Retry MechanismHandle flaky APIs
CI/CDJenkins/GitHub Actions
Database ValidationBackend verification
Schema ValidationValidate JSON structure
Faker LibraryDynamic test data
Parallel ExecutionFaster execution

Real-World Enterprise Structure

framework/
│
├── api/
├── tests/
├── fixtures/
├── utils/
├── helpers/
├── data/
├── reports/
├── logs/
├── schemas/
├── config/
└── .github/workflows/

Best Practices

1. Keep API Logic Separate

Do not write API calls directly inside test files.

✅ Correct:

userAPI.createUser()

❌ Wrong:

request.post(...)

inside every test.


2. Use Environment Variables

BASE_URL=https://uat-api.company.com

3. Validate Response Time

expect(response.ok()).toBeTruthy();

4. Use Soft Assertions Carefully

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

5. Create Reusable Helpers

Example:

  • Token manager
  • Payload builder
  • Common assertions

Advantages of Playwright API Automation

AdvantageDescription
Fast ExecutionNo browser required
Built-in AssertionsEasy validations
API + UI ComboEnd-to-end workflow
Parallel SupportFaster pipelines
TypeScript SupportBetter maintainability
Auto WaitingStable execution

API + UI Hybrid Testing Example

test('Create user via API and validate in UI', async ({ page }) => {

// Create user via API
await userAPI.createUser('Deepesh', 'QA');

// Validate in UI
await page.goto('/users');

await expect(
page.locator('text=Deepesh')
).toBeVisible();
});

Maintain Different Config Files for API and UI Tests

To maintain 2 separate config files for API and UI test cases in frameworks like Playwright Docs, the best approach is to create the following:

  • One config for UI tests
  • One config for API tests

This helps you:

  • Run tests independently
  • Use different base URLs
  • Use different reporters/timeouts
  • Execute API tests faster without browser launch
  • Maintain clean project structure

Recommended Project Structure

project-root/
│
├── tests/
│ ├── ui/
│ │ ├── login.spec.ts
│ │ └── dashboard.spec.ts
│ │
│ └── api/
│ ├── users.spec.ts
│ └── auth.spec.ts
│
├── playwright-ui.config.ts
├── playwright-api.config.ts
│
├── utils/
├── pages/
├── package.json
└── tsconfig.json

1. UI Config File

Create:

playwright-ui.config.ts

import { defineConfig } from '@playwright/test';

export default defineConfig({
testDir: './tests/ui',

timeout: 60000,

use: {
browserName: 'chromium',
headless: false,
baseURL: 'https://example-ui.com',

screenshot: 'only-on-failure',
video: 'retain-on-failure',
trace: 'on-first-retry'
},

reporter: [
['html'],
['list']
],

projects: [
{
name: 'chrome',
use: {
browserName: 'chromium'
}
}
]
});

2. API Config File

Create:

playwright-api.config.ts

import { defineConfig } from '@playwright/test';

export default defineConfig({
testDir: './tests/api',

timeout: 30000,

use: {
baseURL: 'https://api.example.com',

extraHTTPHeaders: {
Accept: 'application/json'
}
},

reporter: [
['html'],
['dot']
],

workers: 4
});

3. Run UI Tests

npx playwright test --config=playwright-ui.config.ts

4. Run API Tests

npx playwright test --config=playwright-api.config.ts

5. Add Package.json Scripts

package.json

{
"scripts": {
"test:ui": "playwright test --config=playwright-ui.config.ts",

"test:api": "playwright test --config=playwright-api.config.ts",

"test:all": "npm run test:ui && npm run test:api"
}
}

6. Environment-Specific Config (Recommended)

You can also maintain:

.env.dev
.env.qa
.env.stage

Install dotenv:

npm install dotenv

Example:

import dotenv from 'dotenv';

dotenv.config({ path: '.env.qa' });

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

7. Better Enterprise Approach (Best Practice)

Many companies use:

configs/
│
├── ui/
│ ├── dev.config.ts
│ ├── qa.config.ts
│ └── stage.config.ts
│
└── api/
├── dev.config.ts
├── qa.config.ts
└── stage.config.ts

This supports:

  • Multiple environments
  • CI/CD pipelines
  • Parallel execution
  • Easy maintenance

8. Common Real-World Usage

TypeSeparate Config Needed?Why
UI TestsYesBrowser settings
API TestsYesNo browser needed
Mobile TestsYesDevice configs
Smoke TestsYesFaster execution
RegressionYesLarge suite handling

9. Advanced Approach Using Base Config

You can avoid duplication using a shared base config.

playwright.base.ts

import { defineConfig } from '@playwright/test';

export default defineConfig({
timeout: 30000,

reporter: 'html'
});

UI Config

import base from './playwright.base';

export default {
...base,

testDir: './tests/ui',

use: {
browserName: 'chromium',
baseURL: 'https://ui.example.com'
}
};

API Config

import base from './playwright.base';

export default {
...base,

testDir: './tests/api',

use: {
baseURL: 'https://api.example.com'
}
};

Best Practice Recommendation

Use:

✅ Separate config files
✅ Shared base config
✅ Environment variables
✅ Separate folders for API/UI
✅ Separate reports
✅ Package.json scripts

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

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);

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 Loop Programs with Solutions

Print numbers from 1 to 10 (Basic for)

for (let i = 1; i <= 10; i++) {
console.log(i);
}

2️⃣ Print numbers from 10 to 1 (Reverse loop)

for (let i = 10; i >= 1; i--) {
console.log(i);
}

3️⃣ Print even numbers (Loop with if)

for (let i = 1; i <= 20; i++) {
if (i % 2 === 0) {
console.log(i);
}
}

4️⃣ Print odd numbers (Loop with if)

for (let i = 1; i <= 20; i++) {
if (i % 2 !== 0) {
console.log(i);
}
}

5️⃣ Sum of numbers from 1 to 10

let sum = 0;for (let i = 1; i <= 10; i++) {
sum += i;
}console.log(sum);

6️⃣ Multiplication table of 5

for (let i = 1; i <= 10; i++) {
console.log(`5 x ${i} = ${5 * i}`);
}

7️⃣ Nested loop: Print square pattern

for (let i = 1; i <= 3; i++) {
let row = "";
for (let j = 1; j <= 3; j++) {
row += "* ";
}
console.log(row);
}

8️⃣ Nested loop: Number pattern

for (let i = 1; i <= 3; i++) {
let row = "";
for (let j = 1; j <= i; j++) {
row += j + " ";
}
console.log(row);
}

9️⃣ while loop: Print 1 to 5

let i = 1;while (i <= 5) {
console.log(i);
i++;
}

🔟 while loop: Sum of first 5 numbers

let i = 1;
let sum = 0;while (i <= 5) {
sum += i;
i++;
}console.log(sum);

1️⃣1️⃣ do...while: Print 1 to 5

let i = 1;do {
console.log(i);
i++;
} while (i <= 5);

1️⃣2️⃣ do...while: Run at least once

let i = 10;do {
console.log(i);
} while (i < 5);

1️⃣3️⃣ forEach: Print array elements

let arr = [10, 20, 30];arr.forEach(num => console.log(num));

1️⃣4️⃣ forEach: Sum of array

let arr = [1, 2, 3, 4];
let sum = 0;arr.forEach(num => {
sum += num;
});console.log(sum);

1️⃣5️⃣ Loop through string (characters)

let str = "Hello";for (let char of str) {
console.log(char);
}

1️⃣6️⃣ Count vowels in a string

let str = "javascript";
let count = 0;for (let char of str) {
if ("aeiou".includes(char)) {
count++;
}
}console.log(count);

1️⃣7️⃣ Loop through array using for

let arr = [5, 10, 15];for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}

1️⃣8️⃣ Find largest number in array

let arr = [10, 5, 20, 8];
let max = arr[0];for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}console.log(max);

1️⃣9️⃣ Loop through object properties (for...in)

let person = {
name: "John",
age: 25,
city: "Delhi"
};for (let key in person) {
console.log(key + ": " + person[key]);
}

2️⃣0️⃣ Count properties in an object

let obj = {
a: 1,
b: 2,
c: 3
};let count = 0;for (let key in obj) {
count++;
}console.log(count);

Beginner Level

  1. Write a JavaScript program to print numbers from 1 to 10 using a for loop.
  2. Write a JavaScript program to print numbers from 10 to 1 in reverse order.
  3. Write a JavaScript program to print all even numbers between 1 and 100.
  4. Write a JavaScript program to print all odd numbers between 1 and 100.
  5. Write a JavaScript program to calculate the sum of numbers from 1 to N.
  6. Write a JavaScript program to calculate the product of numbers from 1 to N.
  7. Write a JavaScript program to print the multiplication table of a given number.
  8. Write a JavaScript program to print the multiplication tables from 1 to 10.
  9. Write a JavaScript program to count the total number of digits in a given number.
  10. Write a JavaScript program to reverse a given number.

Intermediate Level

  1. Write a JavaScript program to check whether a given number is a palindrome.
  2. Write a JavaScript program to find the sum of digits of a given number.
  3. Write a JavaScript program to find the largest digit in a number.
  4. Write a JavaScript program to find the smallest digit in a number.
  5. Write a JavaScript program to calculate the factorial of a number.
  6. Write a JavaScript program to check whether a number is a prime number.
  7. Write a JavaScript program to print all prime numbers between 1 and N.
  8. Write a JavaScript program to count the total number of prime numbers between 1 and N.
  9. Write a JavaScript program to find the sum of all prime numbers between 1 and N.
  10. Write a JavaScript program to print the Fibonacci series up to N terms.

Pattern Programs

  1. Write a JavaScript program to print a right-angled triangle using *.
  2. Write a JavaScript program to print an inverted right-angled triangle.
  3. Write a JavaScript program to print a pyramid pattern using *.
  4. Write a JavaScript program to print an inverted pyramid pattern.
  5. Write a JavaScript program to print a diamond pattern.
  6. Write a JavaScript program to print Floyd’s Triangle.
  7. Write a JavaScript program to print Pascal’s Triangle.
  8. Write a JavaScript program to print a square pattern using *.
  9. Write a JavaScript program to print a hollow square pattern.
  10. Write a JavaScript program to print a hollow pyramid pattern.

Advanced Loop Programs

  1. Write a JavaScript program to find all Armstrong numbers between 1 and N.
  2. Write a JavaScript program to check whether a given number is an Armstrong number.
  3. Write a JavaScript program to find the Greatest Common Divisor (GCD) of two numbers.
  4. Write a JavaScript program to find the Least Common Multiple (LCM) of two numbers.
  5. Write a JavaScript program to convert a decimal number to binary.
  6. Write a JavaScript program to convert a binary number to decimal.
  7. Write a JavaScript program to calculate the power of a number without using built-in methods.
  8. Write a JavaScript program to print all perfect numbers between 1 and N.
  9. Write a JavaScript program to check whether a given number is a perfect number.
  10. Write a JavaScript program to find the sum of all even numbers between 1 and N.

Nested Loop Programs

  1. Write a JavaScript program to print a multiplication table using nested loops.
  2. Write a JavaScript program to print a number triangle pattern.
  3. Write a JavaScript program to print a character triangle pattern.
  4. Write a JavaScript program to print a checkerboard (# and *) pattern.
  5. Write a JavaScript program to print a hollow rectangle using nested loops.
  6. Write a JavaScript program to print an X pattern using *.
  7. Write a JavaScript program to print a butterfly pattern.
  8. Write a JavaScript program to print a sandglass pattern.
  9. Write a JavaScript program to print a zigzag pattern.
  10. Write a JavaScript program to create a simple number guessing game using loops.

JavaScript If-Condition Programs

Here are 20 JavaScript programs with solutions covering:
✔ if
✔ if-else
✔ if-else if
✔ nested if
✔ one-line (ternary) conditions


🔹 1. Positive number (if)

let num = 5;if (num > 0) {
console.log("Positive");
}

🔹 2. Even or odd (if-else)

let num = 4;if (num % 2 === 0) {
console.log("Even");
} else {
console.log("Odd");
}

🔹 3. Voting eligibility (if-else)

let age = 16;if (age >= 18) {
console.log("Eligible");
} else {
console.log("Not eligible");
}

🔹 4. Largest of two numbers (if-else)

let a = 10, b = 20;if (a > b) {
console.log("a is greater");
} else {
console.log("b is greater");
}

🔹 5. Divisible by 3 (if)

let num = 9;if (num % 3 === 0) {
console.log("Divisible by 3");
}

🔹 6. Grade system (if-else if)

let marks = 85;if (marks >= 90) {
console.log("A");
} else if (marks >= 70) {
console.log("B");
} else if (marks >= 50) {
console.log("C");
} else {
console.log("Fail");
}

🔹 7. Largest of three numbers (if-else if)

let a = 5, b = 8, c = 3;if (a > b && a > c) {
console.log("a is largest");
} else if (b > c) {
console.log("b is largest");
} else {
console.log("c is largest");
}

🔹 8. Leap year (if-else)

let year = 2024;if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
console.log("Leap year");
} else {
console.log("Not leap year");
}

🔹 9. Check number range (if)

let num = 25;if (num >= 10 && num <= 50) {
console.log("Within range");
}

🔹 10. Character type (if-else if)

let ch = 'A';if (ch >= 'A' && ch <= 'Z') {
console.log("Uppercase");
} else if (ch >= 'a' && ch <= 'z') {
console.log("Lowercase");
} else {
console.log("Other");
}

🔹 11. Nested if (positive & even)

let num = 8;if (num > 0) {
if (num % 2 === 0) {
console.log("Positive and Even");
}
}

🔹 12. Nested if (login system)

let username = "admin";
let password = "1234";if (username === "admin") {
if (password === "1234") {
console.log("Login successful");
} else {
console.log("Wrong password");
}
} else {
console.log("User not found");
}

🔹 13. Nested if (marks & distinction)

let marks = 75;if (marks >= 40) {
if (marks >= 75) {
console.log("Distinction");
} else {
console.log("Pass");
}
} else {
console.log("Fail");
}

🔹 14. One-line if (ternary)

let num = 10;console.log(num > 0 ? "Positive" : "Not positive");

🔹 15. One-line even/odd

let num = 7;console.log(num % 2 === 0 ? "Even" : "Odd");

🔹 16. One-line pass/fail

let marks = 35;console.log(marks >= 40 ? "Pass" : "Fail");

🔹 17. Multiple conditions (if)

let num = 15;if (num % 3 === 0 && num % 5 === 0) {
console.log("Divisible by 3 and 5");
}

🔹 18. Temperature check (if-else if)

let temp = 30;if (temp > 40) {
console.log("Hot");
} else if (temp > 20) {
console.log("Warm");
} else {
console.log("Cold");
}

🔹 19. Triangle validity (if)

let a = 3, b = 4, c = 5;if (a + b > c && a + c > b && b + c > a) {
console.log("Valid triangle");
}

🔹 20. Simple calculator (if-else if)

let a = 10, b = 5;
let op = "+";if (op === "+") {
console.log(a + b);
} else if (op === "-") {
console.log(a - b);
} else if (op === "*") {
console.log(a * b);
} else if (op === "/") {
console.log(a / b);
} else {
console.log("Invalid operator");
}

JavaScript if Condition Practice Programs (Without Solution)

Beginner Level

  1. Check whether a number is positive.
  2. Check whether a number is negative.
  3. Check whether a number is zero.
  4. Check whether a number is even or odd.
  5. Check whether a person is eligible to vote.
  6. Check whether a student passed or failed.
  7. Find the greater number between two numbers.
  8. Find the smaller number between two numbers.
  9. Check whether a character is a vowel or consonant.
  10. Check whether a year is a leap year.

Intermediate Level

  1. Check whether a number is divisible by 5.
  2. Check whether a number is divisible by both 3 and 7.
  3. Find the largest among three numbers.
  4. Find the smallest among three numbers.
  5. Check whether a character is uppercase or lowercase.
  6. Check whether a number is a 3-digit number.
  7. Check whether a person is a child, teenager, or adult.
  8. Check whether a triangle is valid based on angles.
  9. Check whether a temperature is hot, cold, or moderate.
  10. Calculate bonus based on salary conditions.

Advanced Beginner Level

  1. Check whether a number is divisible by 2 but not by 5.
  2. Check whether a student got distinction, first class, second class, or failed.
  3. Check whether a number is within a given range.
  4. Check whether three sides can form a triangle.
  5. Find the middle number among three numbers.
  6. Check whether a character is an alphabet, digit, or special character.
  7. Check whether a user entered the correct username and password.
  8. Check whether a number is a multiple of 10.
  9. Check whether a person is eligible for a driving license.
  10. Check whether an entered day is weekday or weekend.

Github Guide

Steps to Create a GitHub Account

  1. Go to https://github.com/
  2. Click on the signup button.
  3. Enter email ID
  4. Enter password
  5. Provide a unique Username,
  6. click on the checkbox -> click on the create account button.
  7. It will show some puzzles to verify -> we have to solve.
  8. User will receive a verification code via email -> provide the code on the GitHub screen.
  9. Account creation is Successful.

Steps to Create a GitHub Repository

  1. Go to the GitHub account
  2. Click on the create repository button.
  3. Provide repository name: AutomationPractice
  4. Provide a description. e.g. Automation practice for the user.
  5. Select the Repo visibility option Public/Private.
  6. Select the readme file option.
  7. Click on the Create repository button.
  8. Repository created successfully.

Steps to install the GitHub client

  1. Download the Git client from the given link
    https://github.com/git-for-windows/git/releases/download/v2.53.0.windows.2/Git-2.53.0.2-64-bit.exe
  2. Double-click on the exe file and initiate installation with exe
    , select all default options, and complete the installation.
  3. Create a folder in C Drive with the name GithubCode, folder path should be C:\GithubCode
  4. Open folder and right-click -> show more options -> click on open git bash here.
  5. It will open the Git terminal in the C:\GithubCode folder.
  6. Run a command to check the git option
    git –help
  7. It will show available git commands

Steps to Add User Credentials in Git Config File

  1. Open the Git terminal in the C:\GitHubCode folder
  2. Run the command below to open the config file
    -> git config –global –edit
    -> It will open the config file in the vi editor
  3. Press i to enable insert mode, it should show –insert– in the bottom.
  4. Now use keyboard arrows and update the name and email with your git username and git email.
    [user]
    name = Divya4255
    email = divya.smsrinivas1995@gmail.com
  5. Make sure to remove # from the name and email line in the config file.
  6. Press the ESCAPE key to disabled insert mode.
  7. start type :wq and press enter
    -> It will save the configuration details.

Steps to Clone the Repository on the User’s Machine

  1. Go to the GitHub server, log in with your credentials
  2. Navigate to the repository that we have already created.
  3. Click on the Code (green color) button, and copy the repository from there.
  4. Open the Git terminal in the C:\GitHubCode folder.
  5. Run the command below to clone the repo
    -> git clone https://github.com/Divya4255/AutomationPractice.git
  6. Hit Enter -> It will clone repository from server to your local machine.
  7. The repository folder will be created on the local machine.

Steps to Create a New File and Push to the GitHub Server

  1. Create a text file in the git repository folder (AutomationPractice) and rename as demo_file.txt
  2. Open the text file and add some content to the file -> save the file.
  3. Open the Git terminal in C:\GitHubCode\AutomationPractice folder.
  4. Run the git status command
    -> git status: it will show the new demo file in red color.
  5. Run the git add command
    -> git add file_path/filename # It will add the file to GitHub tracking
  6. Check the status again.
    -> git status # It will show the demo file in green color.
  7. Initiate commit operation
    -> git commit -m “adding new file to repo.”
    -> It will complete the commit operation.
  8. Initiate the git push operation.
    -> git push
    -> It will launch a pop-up
    -> Click and open in browser option.
    -> It will open in browser and click on the Authorize git ecosystem button.
    -> Now push will be successful and file will be push to the server.
    -> Check on GitHub server, the file is available on GitHub server.

Home Work For Practice:

  1. Create three different file and push them to the server.
  2. Update file1 and push(git status, git add, git commit, git push) it.
  3. Rename file2 and push it from the terminal.
  4. Delete file3 and push it from terminal.

Create a Common Repo and Provide Access

  1. Create a repository with the name: e.g., GTM_PlaywrightTS_BATCH11
  2. Get students’ email and provide Access to collaborate.
    Go to Repository -> Settings -> Collaborators -> Add People -> Enter Your email -> Select User -> Add to Repository
  3. People will receive an invitation via email.
  4. Open the email, click View Invitation, then accept the invitation.
  5. Everyone has to accept the invitation.
  6. Make sure to accept the invitation from the laptop, and your GitHub account is already open in the same browser
    where you open the mail account.
  7. Once the invitation is accepted, the user will be able to see the common repository.

Clone the Common Repo, Add folder your name

  1. Go to the common repository -> click on code (green button)
    -> click on copy clipboard to copy URL.
  2. Open the Git terminal in the C:\GitHubCode folder on the local system
  3. Run this command to clone the common repository
    -> git clone https://github.com/sqatools/GTM_PlaywrightTS_BATCH11.git
  4. It will clone the command repository into a C:\GitHubCode to the local directory.
    -> repository folder name: GTM_PlaywrightTS_BATCH11
  5. Create folder with your name in repo e.g. Deepesh and Add file inside the your folder e.g. first_file.txt
  6. Navigate back to git terminal.
  7. ON git terminal run below command to go inside repository folder.
    cd GTM_PlaywrightTS_BATCH11 -> It will open GTM_PlaywrightTS_BATCH11 folder.
  8. Check status using below command
    -> git status : New Folder name will show in red color.
  9. Run git add command
    -> git add /FolderName
  10. Initiate commit operation.
    -> git commit -m “added”
  11. Perform git push operation
    -> git push
  12. If push is rejected repeat this steps until push it not successful.
    -> git pull
    -> it will open merge editor
    -> we have to close the edit with command using :wq (save file)
    -> Once the edit is closed, re-initiate the push operation
    -> git push
    -> if push is still rejected (Repeat again from “git pull” command)
################ Multi branching in git
  1. Go to Git Repository on server : GTM_PlaywrightTS_BATCH11
  2. Click on repository dropdown. default is main
  3. click on view all branches.
  4. Create branch with your name e.g. deepesh_branch.
    -> New Branch
    -> Provide Branch Name e.g. firstname_branch
    -> click on create branch button
    -> Verify branch is created successfully.
  5. Open git terminal in repository folder
  6. run command to update the repo
    -> git pull (all newly created branches will show in the console output)
  7. Check current active branch
    -> git branch : It will show main as active branch in green color.
  8. Switch to new branch.
    -> git checkout deepesh_branch
  9. check again active branch
    -> git branch : your branch will show as active branch in green color e.g. deepesh_branch
  10. Go to your dedicated folder and add file inside the folder
    Folder Name : Deepesh
    Filename : deepesh_feature_file.txt (don’t add space in filename)

11 Go back to terminal and check status
-> git status : newly added file will show in red color

  1. Run git add command
    -> git add
  2. Initiate commit operation
    -> git commit -m “added new file to feature branch”
  3. Initiate push operation
    -> git push : file will push to the server on dedicated branch.
  4. Go to GitHub server and verify file is available in dedicated folder in your branch.
################### Create pull from server
  1. Go to server and navigate to repository.
  2. Click on “Compare & pull request” button (green button)
  3. Provide pull request description.
  4. Add reviwers to review the code.
  5. Click on create pull button.
################### Create workflow file in branch
  1. Go to repository on GitHub server
  2. Navigate to Actions Tab.
  3. Click on New Workflow (green color) button
  4. Select any workflow from given list. e.g. simple workflow
  5. click on configure button
  6. Select your branch from left side dropdown e.g. deepesh_branch.
  7. Provide workflow name default name is blank.yml
    default path: GTM_Playwright_Batch11/.gitHub/workflow/blank.yml keep this path alive
    pull_request:
    branches: [ “main” ] remove this part: this will execute workflow for every single push
    push:
    branches: [ “main” ]
  8. click on commit changes button.
  9. It will open pop to provide commit message -> we can click on commit changes
    and push to the current branch.
  10. It will create workflow on your dedicated branch and execute along with each
    PR.
########## Resolve Merge conflict

conflict scenario

  1. Create file1 in main branch add some code from line 1 to 10.
  2. Create new branch from main branch and then modify same file1 and same line numbers from 1 to 10.
  3. In main branch, modify same on same number of lines and push it.
  4. Create pull request from feature to main branch
  5. It will create conflict.
  6. We have to resolve conflict and merge the change
Steps to reproduce conflict scenario
  1. Open git terminal in repository folder.
    -> make sure your current active branch should be main
    -> if not then you can switch to main branch.
    -> ‘git checkout main’ # it will switch to main branch.
    -> ‘git pull’ : Update your main branch with all change from server.
    -> ‘git branch’ : current active branch should be main branch in green color
  2. Create a file with name e.g. dy_conflict_file.txt, and code snipet in the file, and save the file.
    var num1 = 10
    if (num1%2 == 0) {
    console.log(“This is even number”)
    } else {
    console.log(“This is odd number”)
    }
  3. Push file to main branch.
    -> git status: show file in read color
    -> git add
    -> git status : show file in green color
    -> git commit -m “added file”
    -> git push : It push is rejected, then pull the code and perform push operation.
    -> git pull : it will open editor, we have close it with :wq! command.
    -> then try to push again, repeat (pull, push), until it is not successful.
  4. Create a branch from local git bash terminal.
    -> git checkout -b “dy_conflict_branch”
  5. Update dy_conflict_file.txt file as given below. if (num1%2 == 0) {
    console.log(“This is even number, divisible by 2”)
    } else {
    console.log(“This is odd number, not divisible by 2”)
    }
  6. go back to terminal and run below command
    -> git status : shows in red color
    -> git add
    -> git status : shows file in green color
    -> git commit -m “initiate commit operation”
  7. run below command to push local branch to server
    -> git push –set-upstream origin dy_conflict_branch
    -> push will be successful in feature.
  8. change branch from conflict branch to main branch in terminal
    -> git checkout main
    -> git pull : it will update all changes from server to local machine.
  9. Open conflict file in your folder and update few change in file content.
    var num1 = 10
    if (num1%2 == 0) {
    console.log(“condition is True”)
    console.log(“This is even number, can divide by 2”)
    } else {
    console.log(“condition is False”)
    console.log(“This is odd number, can not divide by 2”)
    }
  10. push the file change in main branch.
    -> git status
    -> git add
    -> git commit -m “updated file”
    -> git push (repeat pull and push commands)
  11. Go to GitHub server and create pull request from conflict branch to main branch
    -> go to repository
    -> search your branch name and select the branch.
    -> if the branch is old, then it will show contribute button
    -> click on contribute button and click on ‘Open pull request’ button.
    -> Provide request details (reviewer, description assignee)
    -> click on create pull request button.
  12. It will show merge conflict between main branch and feature branch.
    -> ‘merge pull request’ button will be in disable state. This branch has conflicts that must be resolved
    Use the web editor or the command line to resolve conflicts before continuing. Deepesh/dy_conflict_file.txt

—— Resolve merge conflict locally ——

  1. Go back to git terminal
  2. switch to feature branch.
    -> git checkout dy_conflict_branch
  3. run a command on terminal to update feature branch with main branch
    -> git pull origin main
    -> it will show conflict message on terminal Auto-merging Deepesh/dy_conflict_file.txt CONFLICT (content): Merge conflict in Deepesh/dy_conflict_file.txt Automatic merge failed; fix conflicts and then commit the result.
  4. Open dy_conflict_file.txt on local machine, will show below content

var num1 = 10
if (num1%2 == 0) {

HEAD : change from feature BRANCH (dy_conflict_branch)

<<<<<<< HEAD
console.log(“This is even number, divisible by 2”)
} else {

console.log(“This is odd number, not divisible by 2”)

Changes from MAIN branch

console.log(“condition is True”)
console.log(“This is even number, can divide by 2”)
} else {
console.log(“condition is False”)
console.log(“This is odd number, can not divide by 2”)

9f9d33c6d4f9d945d512c3b40e36783b758295fd
}

  1. Update the file content as per your requirements. var num1 = 10
    if (num1%2 == 0) {
    console.log(“condition is True”)
    console.log(“This is even number, divisible by 2”)
    } else {
    console.log(“condition is False”)
    console.log(“This is odd number, not divisible by 2”)
    }
  2. go to git terminal and run below commands
    -> git status : It will show in red color
    -> git add
    -> git commit -m “resolved merge”
    -> git push
  3. Once the push is successful, merge will conflict will be resolved in pull request
    -> Now go back to git server and check pull request, there is no conflict anymore.
  4. We can merge changes from feature to main branch.