Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
7 views7 pages

Playwright JS

The document provides a comprehensive guide on using Playwright for testing, including syntax for defining tests, grouping tests with test.describe(), and setting up common logic with test.beforeEach(). It explains the use of fixtures like browser, page, and context, and details how to manage cookies, local storage, and permissions. Additionally, it covers best practices and the use of test.only() for focused testing.

Uploaded by

Manikant Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views7 pages

Playwright JS

The document provides a comprehensive guide on using Playwright for testing, including syntax for defining tests, grouping tests with test.describe(), and setting up common logic with test.beforeEach(). It explains the use of fixtures like browser, page, and context, and details how to manage cookies, local storage, and permissions. Additionally, it covers best practices and the use of test.only() for focused testing.

Uploaded by

Manikant Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Playwright

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

test('First Playwright Test',async ({browser,page})=>{

// const context = await browser.newContext();


// const page = await context.newPage();
await page.goto('https://google.com');
});

✅ Playwright test() — Usage and Fixtures

Basic Syntax:

test('test name', async ({ fixtures }) => {


// test logic
});

1. Fixtures (Injected Context)

Playwright Test runner injects an object with helpful tools:

{ browser, page, context, browserName, playwright }

You must destructure the object to use them.

Example using 'page' fixture:

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

test('with injected page', async ({ page }) => {


await page.goto('https://example.com');
await expect(page).toHaveTitle(/Example Domain/);
});

❌ Wrong Usage: Passing 'browser' directly

test('wrong usage', async (browser) => {


// browser will be undefined or cause error
});

✅ Correct usage with 'browser'

test('correct usage', async ({ browser }) => {


const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://example.com');
});
test.describe() to group related tests:
test.describe('Login tests', () => {
test('valid login', async ({ page }) => {
await page.goto('https://example.com/login');
});

test('invalid login', async ({ page }) => {


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

test.beforeEach() and test.afterEach():


test.describe('Tests with common setup', () => {
test.beforeEach(async ({ page }) => {
await page.goto('https://example.com');
});

test('Check homepage', async ({ page }) => {


await expect(page.locator('h1')).toContainText('Example');
});
});

✅ Playwright Test Structure: test() vs test.describe() vs test.beforeEach()

🔹 test() – Define Individual Tests

- Used to write a single test case.

- Receives a test name and an async callback.

- The callback is injected with useful fixtures (e.g., page, browser, context).

Syntax:

test('should load homepage', async ({ page }) => {


await page.goto('https://example.com');
await expect(page).toHaveTitle(/Example Domain/);
});

🔹 test.describe() – Group Related Tests

- Used to logically group multiple related test cases.

- Helps with organizing tests and applying common hooks (beforeEach, afterEach) at the
group level.

- Optional, but improves clarity in test reports.

Syntax:
test.describe('Login Flow', () => {
test('valid login', async ({ page }) => {
await page.goto('https://example.com/login');
// Perform valid login steps
});

test('invalid login', async ({ page }) => {


await page.goto('https://example.com/login');
// Attempt login with invalid credentials
});
});

🔹 test.beforeEach() – Setup Logic Before Each Test

- Runs before every test() in its scope.

- Can be placed globally or inside a test.describe() block.

- Useful for navigation, test data setup, authentication, etc.

Syntax (inside describe block):

test.describe('Dashboard Tests', () => {


test.beforeEach(async ({ page }) => {
await page.goto('https://example.com/dashboard');
// Common pre-test setup like login
});

test('check widget visibility', async ({ page }) => {


await expect(page.locator('.widget')).toBeVisible();
});

test('verify chart loads', async ({ page }) => {


await expect(page.locator('#chart')).toBeVisible();
});
});

Global beforeEach (outside describe):

test.beforeEach(async ({ page }) => {


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

🔄 How They Work Together

| Function | Purpose | Scope |

|-------------------|----------------------------------------|------------------|

| test() | Defines a single test case | Individual test |

| test.describe() | Groups multiple related tests | Logical grouping |


| test.beforeEach() | Runs setup before each test | Per group/global |

🧠 Best Practices

- Use test.describe() to organize tests by feature/module.

- Use test.beforeEach() to avoid repeating setup code.

- Keep test() clean — only include logic specific to the test case.

Fixtures Summary:

page - Pre-created browser tab (isolated per test)

browser - Shared browser instance (manual context creation needed)

context - New browser context per test (like a fresh profile)

browserName - Current browser (chromium, firefox, webkit)

playwright - Access to devices, selectors, and all browser types

Recommended Default: Use { page }

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


await page.goto('https://playwright.dev');
await expect(page).toHaveTitle(/Playwright/);
});

✅ Playwright `context` – Detailed Explanation + Usage for Cookies, Storage & Extensions

🔹 What is `context`?

- A **browser context** is like a **separate, isolated browser profile**.

- It has its own **cookies**, **local storage**, **session storage**, and **permissions**.

- Think of it as an **incognito window** in Chrome — isolated from other windows.

🔹 Why use `context`?

- Simulate multiple users in one test.

- Load predefined cookies or local storage to skip login.

- Control browser-level settings like permissions.

- Use browser extensions (e.g., ad blocker, password manager).

🔹 Basic Usage Example:

test('manual context creation', async ({ browser }) => {


const context = await browser.newContext(); // Create new isolated
profile
const page = await context.newPage();
await page.goto('https://example.com');
await context.close(); // Clean up
});

If we are not setting anything like coockies or proxy in context then we can directly use
page fixture and avoid using browser as page directly will give incognito like context.

test('First Playwright Test',async ({browser,page})=>{

// const context = await browser.newContext();


// const page = await context.newPage();
await page.goto('https://google.com');
});

1. Load Cookies into Context (skip login)

test('load cookies into context', async ({ browser }) => {


const context = await browser.newContext({
storageState: 'auth.json' // Load cookies + localStorage from file
});
const page = await context.newPage();
await page.goto('https://example.com/dashboard');
});

➡️First, save the storage state after login:

test('login and save cookies', async ({ page }) => {


await page.goto('https://example.com/login');
await page.fill('#username', 'user');
await page.fill('#password', 'pass');
await page.click('text=Login');
await page.context().storageState({ path: 'auth.json' });
});

🔹 2. Set Cookies Programmatically

test('set cookies manually', async ({ browser }) => {


const context = await browser.newContext();
await context.addCookies([
{
name: 'session_id',
value: 'abc123',
domain: 'example.com',
path: '/',
httpOnly: true,
secure: true,
sameSite: 'Lax'
}
]);
const page = await context.newPage();
await page.goto('https://example.com');
});

🔹 3. Use Browser Context to Simulate Local Storage

test('set localStorage before page load', async ({ browser }) => {


const context = await browser.newContext();
const page = await context.newPage();
await page.addInitScript(() => {
window.localStorage.setItem('theme', 'dark');
});
await page.goto('https://example.com');
});

🔹 4. Use Extensions with Context (Chromium-only)

const context = await chromium.launchPersistentContext('user-data-dir', {


headless: false,
args: [
`--disable-extensions-except=./my-extension`,
`--load-extension=./my-extension`
]
});
const page = await context.newPage();
await page.goto('chrome-extension://<extension-id>/popup.html');

🔸 Note:

 This requires launchPersistentContext (not browser.newContext)

 launchPersistentContext uses a real profile with permanent storage

 Only available in Chromium

🔹 5. Grant Permissions (like camera/mic/geo)

const context = await browser.newContext({


permissions: ['geolocation'],
geolocation: { latitude: 12.97, longitude: 77.59 },
});
const page = await context.newPage();
await page.goto('https://maps.example.com');

🔹 Summary of What context Can Do:

Feature How to Use

Isolated session browser.newContext()

Load cookies storageState: 'auth.json' or addCookies()

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


Feature How to Use

Local storage page.addInitScript() before navigation

Permissions newContext({ permissions: [...] })

Extensions chromium.launchPersistentContext() with args

✅ Playwright `test.only()` – Run a Single Test or Suite Exclusively


🔹 What is `test.only()`?

- It tells Playwright to run **only that one test** (or test group).

- All other tests are skipped — useful during debugging or focused development.

🔹 1. Run a Single Test

test.only('runs this test only', async ({ page }) => {


await page.goto('https://example.com');
await expect(page).toHaveTitle(/Example Domain/);
});

2. Use Inside test.describe.only() for a Suite

test.describe.only('Auth Tests', () => {


test('valid login', async ({ page }) => {
// ...
});

test('invalid login', async ({ page }) => {


// ...
});
});

🛑 Warning:

 Don’t forget to remove test.only() before pushing to main or running CI.

 CI pipelines will skip all other tests if .only() is accidentally left in.

🧠 Tip:

 Add .only temporarily while debugging or writing.

 Use npx playwright test --forbid-only in CI to fail builds that include .only.

//expect in playwright
await expect(page.locator("//span[text()='Hello, Manikant']"))
.toContainText("Hello, Manikant");

You might also like