async and await are used to work with asynchronous code in JavaScript. They are essential when dealing with operations that take time to complete, such as network requests or file operations.
async: This keyword is used to define an asynchronous function.
await: This keyword is used to wait for a Promise to resolve before continuing execution.
- page.goto(): This command navigates the browser to the Google homepage.
- page.url(): This retrieves the current URL of the page.
- page.title(): Retrieves the current page's title.
Simple example to launch browser page in playwright, validating page title and page URL.
// @ts-check import { test, expect } from '@playwright/test'; import { chromium } from 'playwright'; test('Search skptricks in google search engine', async () => { const browser = await chromium.launch({ headless: false, args: ['--disable-blink-features=AutomationControlled'],}) const page = await browser.newPage(); await page.goto('https://www.google.com/'); // Check page URL. const pageURL = await page.url(); console.log("Page URL is : "+ pageURL) await expect(page).toHaveURL('https://www.google.com/'); await page.locator("[name='q']").fill("skptricks"); await page.keyboard.press('Enter'); await expect(await page.locator("[name='q']")).toHaveValue('skptricks'); // Check Page Title. const pageTitle = await page.title(); console.log("Page Title is : "+ pageTitle) await expect(page).toHaveTitle('skptricks - Google Search'); // Check page partial URL check. const pagePartialURLCheck = await page.url(); console.log("Page URL is : "+ pagePartialURLCheck) await expect(pagePartialURLCheck).toContain('https://www.google.com/search?q=skptricks&'); await browser.close(); });
Output :
npx playwright test first.spec.js --project=chromium --headed Running 1 test using 1 worker [chromium] › tests\first.spec.js:5:5 › Search skptricks in google search engine Page URL is : https://www.google.com/ Page Title is : skptricks - Google Search Page URL is : https://www.google.com/search?q=skptricks&sca_esv=13bc179c92138921&source=hp&ei=3YbpZ53GApmF2roP3szY6Qo&iflsig=ACkRmUkAAAAAZ-mU7WDMtqJFZWL2WTHUsmUCet9WAMnM&ved=0ahUKEwjdqOmwsbKMAxWZglYBHV4mNq0Q4dUDCBA&uact=5&oq=skptricks&gs_lp=Egdnd3Mtd2l6Iglza3B0cmlja3NIDVAAWABwAHgAkAEAmAEAoAEAqgEAuAEDyAEA-AEBmAIAoAIAmAMAkgcAoAcA&sclient=gws-wiz&sei=3obpZ_7sJf3j2roPiOydyAc 1 passed (5.2s) To open last HTML report run: npx playwright show-report
This test automates the process of searching for the term "skptricks" on Google using Playwright, checks that the page loads correctly, verifies that the search term appears in the search box after submission, confirms the page title is correct, and ensures the URL contains the expected search query parameters.
No comments:
Post a Comment