11. How to open a browser in playwright ?
There are two common ways to open a browser in Playwright: using the built-in page fixture and launching the browser manually.
1. Using the Playwright fixture
import { test } from '@playwright/test';
test('open a browser', async ({ page }) => {
await page.goto('https://www.example.com/');
});
In this:
Playwright automatically creates the browser, browser context, and page.
You can directly use page.goto() to navigate to a URL.
Playwright manages the browser lifecycle for you.
2. Without using the Playwright fixture import { test, chromium } from '@playwright/test';
test('open a browser', async () => {
const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage(); await page.goto('https://www.example.com/');
await browser.close();
});
In this:
You manually launch the browser using chromium.launch().
You create a browser context and a page.
You are responsible for closing the browser. 12. How do you correlate the Browser, Context, and Page in Playwright?
Let's start with the Page.
- Page: A Page represents a single browser tab or a window within a browser context.
- Context: A Browser Context is an isolated browser session(isolated window or new window). It has its own cookies, local storage, session storage, and other session-related data. Multiple pages within the same context share the context's applicable session data. Separate contexts are isolated from each other. For example, two separate contexts(windows) can represent two different users.
- Browser: A Browser represents an instance of a browser engine, such as Chromium, Firefox, or WebKit. A browser instance can contain multiple browser contexts, and each context can contain multiple pages.
Hierarchy:
Browser
├── Context 1 (User A)
│ ├── Page 1 (Tab 1)
│ └── Page 2 (Tab 2)
└── Context 2 (User B)
└── Page 3 (Tab 1)
In short, a Browser contains contexts, and each Context contains pages. Pages within the same context share applicable session data, while separate contexts provide isolated sessions.
13. How to add or import modules or packages in any playwright class ?
In java script, we can import like this:
import { test, expect, Page } from '@playwright/test';
import { Helper } from './utils/helpers';
import { testClass1,testClass2 } from './tests/folder1/testClass'; // here the methods testClass1and testClass2 have been imported from the class tests/folder1/testClass.js
or
const { test, expect, Page } = require( '@playwright/test');
const { Helper } = require( './utils/helpers');
const { testClass1,testClass2 } = require( './tests/folder1/testClass');
Some points to remember:
test and expect are Playwright exports.
Helper must be exported from utils/helpers.js.
testClass1 and testClass2 must be exported from testClass.js.
Page is a TypeScript type, not a runtime JavaScript export you normally need. If you're writing plain JavaScript, remove it from the import.
In above example, your class testClass.js file could look like this:
export class testClass1 {
method1_class1() {
console.log('Method1_class1');
}
method2_class1() {
console.log('Method2_class1');
}
}
export class testClass2 {
method1_class2() {
console.log('Method1_class2');
}
}
//-------------------------------------------------------Then use the classes in your importing test:import { test, expect } from '@playwright/test';import { testClass1, testClass2 } from './tests/folder1/testClass';test('example', async ({ page }) => {const obj1 = new testClass1();const obj2 = new testClass2();obj1.method1_class1();obj1.method2_class1();obj2.method1_class2();});
class testClass1 {
method1_class1() {
console.log('Method1_class1');
}
method2_class1() {
console.log('Method2_class1');
}
}
class testClass2 {
method1_class2() {
console.log('Method1_class2');
}
}
module.exports = { testClass1, testClass2 };
//-------------------------------------------------------
Then use the classes in your importing test:
const { test, expect } = require('@playwright/test');
const { testClass1, testClass2 } = require('./tests/folder1/testClass');
test('example', async ({ page }) => {
const obj1 = new testClass1();
const obj2 = new testClass2();
obj1.method1_class1();
obj1.method2_class1();
obj2.method1_class2();
});
16. How do you record in Playwright?
We can record user actions in Playwright using the Codegen tool. It opens a browser and the Playwright Inspector, records our actions, and generates Playwright code.
Common Codegen commands:
npx playwright codegen— Opens the browser and Playwright Inspector.npx playwright codegen https://www.google.com— Opens the specified URL directly.npx playwright codegen --browser firefox— Launches Firefox instead of the default Chromium browser.npx playwright codegen --viewport-size="600,600"— Sets the browser viewport to 600 × 600 pixels.npx playwright codegen --device="iPhone X"— Emulates an iPhone X device (the device name must be supported).npx playwright codegen --color-scheme=dark— Emulates dark color scheme preferences.npx playwright codegen --help— Displays available Codegen options.
17. What are the hooks in Playwright?
Playwright has four main hooks:
beforeAll()— Runs once before all tests in the current scope.afterAll()— Runs once after all tests in the current scope.beforeEach()— Runs before each test.afterEach()— Runs after each test.
Note: When hooks are defined inside a test.describe() block, they apply to the tests within that block. When defined outside a describe block, they generally apply to tests in the file.
18. What are assertions in Playwright?
Assertions are used to verify whether the actual result matches the expected result in a test. Playwright provides the expect() function to perform assertions.
Common assertions in Playwright:
await expect(page).toHaveTitle('Home Page');await expect(page).toHaveURL('https://example.com');await expect(page.locator('#username')).toBeVisible();
await expect(page.locator('#username')).toBeEnabled();
await expect(page.locator('#username')).toHaveText('John');
await expect(page.locator('#username')).toHaveValue('John');
await expect(page.locator('#checkbox')).toBeChecked();
await expect(page.locator('.message')).toContainText('Success');
await expect(page.locator('#username')).toHaveCount(1);
await expect(page.locator('#username')).toHaveAttribute('id', 'username');
await expect(page.locator('#username')).toHaveClass('username-field');
Using not:
We can use ".not" to verify that a condition is false.
await expect(page.locator('#username')).not.toBeVisible();await expect(page.locator('#username')).not.toBeEnabled();await expect(page.locator('#username')).not.toHaveText('John');await expect(page.locator('#username')).not.toHaveValue('John');
19. What are Hard and soft assertions in Playwright ?
- Hard assertion: It is the default assertion. If this fails, the test stops at that point.
- Soft assertion: This uses
"expect.soft()." If thsi fails, the test continues, and the failure is reported at the end.
Example:
await expect.soft(page.locator('#username')).toBeVisible();
await expect.soft(page.locator('#username')).not.toBeEnabled();
20. What are annotations in Playwright?
Annotations are used to control test execution based on specific requirements.Common annotations in Playwright:1. only — Runs only the specified test or test group. Use it carefully because it can cause other tests to be excluded.test.only('example', async ({ page }) => { // Runs this test only});2. skip — Skips the test without executing it.test.skip('example', async ({ page }) => { // This test is skipped});3. fail — Marks a test as expected to fail, ie, to intentionally fail a test case. If it passes, Playwright reports an unexpected pass.test.fail('example', async ({ page }) => { // This test is expected to fail});4. fixme — Marks a test as needing a fix and skips its execution.test.fixme('example', async ({ page }) => { // This test is not executed});5. slow — Marks a test as slow and triples its test timeout compared to the default or configured timeout.test('example', async ({ page }) => { test.slow(); // Test steps});6. skip conditionally : Used to skip a test when a specified condition is met.test('example', async ({ page, browserName }) => { test.skip(browserName === 'firefox', 'Skip this test in Firefox'); // Test steps});Explanation: The test is skipped only when the browser is Firefox. Otherwise, the test executes normally.
21. How to Generate and Open a Report in Playwright ?
There are two common ways to generate reports in Playwright.
1. From the Command Line
To generate an HTML report while executing tests, run:
npx playwright test --reporter=html
After the execution finishes, open the report using:
npx playwright show-report
2. From the playwright.config.js File
Configure the reporters in the Playwright configuration file:
export default defineConfig({
reporter: [
['list'],
['html', { open: 'never' }],
['json', { outputFile: 'test-report.json' }],
],
});
Playwright provides built-in reporters, including List, HTML, and JSON.
- List: Displays test execution results in the terminal.
- HTML: Generates an interactive HTML report.
- JSON: Generates a JSON report, which is useful for further processing. In this example, the report is saved as test-report.json in the project root directory.
Common HTML Reporter Options
- ['html', { open: 'never' }]: Generates the HTML report but does not automatically open it.
- ['html', { open: 'always' }]: Generates the HTML report and automatically opens it after the test run.
- ['html', { open: 'on-failure' }]: Automatically opens the HTML report only if the test run fails.
Note: The default HTML reporter option is open: 'on-failure'.
22. How to Handle Multiple Tabs in Playwright?
In Playwright, we use context.waitForEvent('page')
to detect a newly opened tab and then interact with it.
Example (JavaScript)
import { test, expect } from '@playwright/test'; test('Handle multiple tabs', async ({ page, context }) => { await page.goto('https://example.com'); // Open a new tab by clicking a link const newTabPromise = context.waitForEvent('page'); await page.getByText('Open new tab').click(); const newTab = await newTabPromise; // Interact with the new tab await newTab.waitForLoadState(); console.log(await newTab.title()); await expect(newTab).toHaveTitle('HomePage');});In simple terms
context.waitForEvent('page')— Waits for a new tab or page to open.newTab— Represents the newly opened tab.- We use
newTabto interact with elements in the new tab.