"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Automation using Playwright and TypeScript and JavaScript

Automation using Playwright and TypeScript and JavaScript

Published on 2024-11-08
Browse:315

Playwright With TypeScript | JavaScript Installation

Playwright is the modern web based and API Automation tool from Microsoft by collaborating with Puppeteer team, Puppeteer is a JavaScript library which provides a high-level API to control Chrome or Firefox over the DevTools Protocol or WebDriver BiDi. Puppeteer runs in the headless (no visible UI) by default.

Playwright supports the modern web based browsers for automation of web application though single API and also supports the automation for API.

Architecture of Playwright

Automation using Playwright and TypeScript and JavaScript

Playwright works on Web Socket Protocol once connection is established will triggers the tests and sends the request in the JSON format to server using Web Socket Protocol which means once connection established by Playwright no need to establish the connection again for sending the requests to server until the complete test execution. Playwright has to disconnect the connection by playwright.quit() method.

Lets us understand the difference between HTTP Protocol Connection Web Socket Protocol Connection

Automation using Playwright and TypeScript and JavaScript

Difference between WebSocket & HTTP Protocol
Features of Playwright :
Any browser • Any platform • One API
Cross-browser. Playwright supports all modern rendering engines including Chromium, WebKit, and Firefox.

Cross-platform. Test on Windows, Linux, and macOS, locally or on CI, headless or headed.

Cross-language. Use the Playwright API in TypeScript, JavaScript, Python, .NET, Java.

Test Mobile Web. Native mobile emulation of Google Chrome for Android and Mobile Safari. The same rendering engine works on your Desktop and in the Cloud.

  1. Resilient • No flaky tests

Auto-wait. Playwright waits for elements to be actionable prior to performing actions. It also has a rich set of introspection events. The combination of the two eliminates the need for artificial timeouts — the primary cause of flaky tests.

Web-first assertions. Playwright assertions are created specifically for the dynamic web. Checks are automatically retried until the necessary conditions are met.

Tracing. Configure test retry strategy, capture execution trace, videos, screenshots to eliminate flakes.

  1. No trade-offs • No limits

Browsers run web content belonging to different origins in different processes. Playwright is aligned with the modern browsers architecture and runs tests out-of-process. This makes Playwright free of the typical in-process test runner limitations.

Multiple everything. Test scenarios that span multiple tabs, multiple origins and multiple users. Create scenarios with different contexts for different users and run them against your server, all in one test.

Trusted events. Hover elements, interact with dynamic controls, produce trusted events. Playwright uses real browser input pipeline indistinguishable from the real user.

Test frames, pierce Shadow DOM. Playwright selectors pierce shadow DOM and allow entering frames seamlessly.

  1. Full isolation • Fast execution

Browser contexts. Playwright creates a browser context for each test. Browser context is equivalent to a brand new browser profile. This delivers full test isolation with zero overhead. Creating a new browser context only takes a handful of milliseconds.

Log in once. Save the authentication state of the context and reuse it in all the tests. This bypasses repetitive log-in operations in each test, yet delivers full isolation of independent tests.

  1. Powerful Tooling

Codegen. Generate tests by recording your actions. Save them into any language.

Playwright inspector. Inspect page, generate selectors, step through the test execution, see click points, explore execution logs.

Trace Viewer. Capture all the information to investigate the test failure. Playwright trace contains test execution screencast, live DOM snapshots, action explorer, test source, and many more.

Let us start using Playwright with TypeScript/JavaScript

Installation of Playwright for TypeScript/JavaScript
Pre-requisites for installation as follows : Node.js 18

Windows 10 , Windows Server 2016 or Windows Subsystem for Linux (WSL).
macOS 13 Ventura, or macOS 14 Sonoma.
Debian 11, Debian 12, Ubuntu 20.04 or Ubuntu 22.04, Ubuntu 24.04, on x86–64 and arm64 architecture.
Get started by installing Playwright using npm, yarn or pnpm. Alternatively you can also get started and run your tests using the VS Code Extension.

Create the folder, for example TypeScriptWithPlaywright likewise create folder for JavaScriptwithPlaywright and navigate to folder and open the command prompt of the windows

Automation using Playwright and TypeScript and JavaScript

Playwright Installation
Click on the enter and following screen will appear and choose the Scripting language and then press the enter

Automation using Playwright and TypeScript and JavaScript

Select the Scripting Language
After selecting the scripting language and then press enter following screen will appear and will ask where you want to put your end to end tests. lets be it like that.

Playwright Installation
Now it will ask for GitHub Actions workflow. If you want to configure then Press Y or else N. It will ask you for to install browser, if you want to install then Select Y which means true. following screen will appear.

Automation using Playwright and TypeScript and JavaScript

Note : Playwright browsers can be installed by manually via below command

Automation using Playwright and TypeScript and JavaScript

npx playwright install

Playwright Installation
Now press enter and the following screens will appear.

Automation using Playwright and TypeScript and JavaScript

Playwright Installation
Playwright Installation

Playwright Installation

Playwright Installation Complete
Playwright by default executes the test scripts which is executed in headless mode and following commands will explore to execute with specific browsers and debug, generating test scripts using codegen.

npx playwright test
Runs the end-to-end tests.

npx playwright test --ui
Starts the interactive UI mode.

npx playwright test --project=chromium
Runs the tests only on Desktop Chrome.

npx playwright test example
Runs the tests in a specific file.

npx playwright test --debug
Runs the tests in debug mode.

npx playwright codegen
Auto generate tests with Codegen.

We suggest that you begin by typing:

npx playwright test

Now lets execute the test scripts by using the following command and to view the report. Playwright will execute the tests in chromium, Firefox and WebKit Parallelly.

npx playwright test

npx playwright show-report

Playwright by default report supports only TypeScript/JavaScript
Playwright by default configure your test scripts to execute in the following browsers with headless mode. The configuration will present in the folder named as playwright.config.js

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

/**

  • Read environment variables from file.
  • https://github.com/motdotla/dotenv */ // import dotenv from 'dotenv'; // import path from 'path'; // dotenv.config({ path: path.resolve(__dirname, '.env') });

/**

  • See https://playwright.dev/docs/test-configuration.
    /
    export default defineConfig({
    testDir: './tests',
    /
    Run tests in files in parallel /
    fullyParallel: true,
    /
    Fail the build on CI if you accidentally left test.only in the source code. /
    forbidOnly: !!process.env.CI,
    /
    Retry on CI only /
    retries: process.env.CI ? 2 : 0,
    /
    Opt out of parallel tests on CI. /
    workers: process.env.CI ? 1 : undefined,
    /
    Reporter to use. See https://playwright.dev/docs/test-reporters /
    reporter: 'html',
    /
    Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. /
    use: {
    /
    Base URL to use in actions like await page.goto('/'). */
    // baseURL: 'http://127.0.0.1:3000',

    /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
    trace: 'on-first-retry',
    },

/* Configure projects for major browsers */
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},

{
  name: 'firefox',
  use: { ...devices['Desktop Firefox'] },
},

{
  name: 'webkit',
  use: { ...devices['Desktop Safari'] },
},

/* Test against mobile viewports. */
// {
//   name: 'Mobile Chrome',
//   use: { ...devices['Pixel 5'] },
// },
// {
//   name: 'Mobile Safari',
//   use: { ...devices['iPhone 12'] },
// },

/* Test against branded browsers. */
// {
//   name: 'Microsoft Edge',
//   use: { ...devices['Desktop Edge'], channel: 'msedge' },
// },
// {
//   name: 'Google Chrome',
//   use: { ...devices['Desktop Chrome'], channel: 'chrome' },
// },

],

/* Run your local dev server before starting the tests */
// webServer: {
// command: 'npm run start',
// url: 'http://127.0.0.1:3000',
// reuseExistingServer: !process.env.CI,
// },
});
Now let us modify to execute the test scripts non headleases mode( UI) and with adding additional browsers. Playwright also provides the options for to record the test script execution and trace view options which will be useful for debugging. If you enable the trace viewer option can able to see what is the status before test, what is the status during test and what would be status after test. I have modified the playwright config file and it is as below :

// @ts-check
const { defineConfig, devices } = require('@playwright/test');

module.exports = defineConfig({
testDir: './tests',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: 'html',
use: {
trace: 'on', // Enable tracing
video: 'on', // Record video for each test
headless: false, // Run tests in headed mode
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] },
},
{
name: 'Microsoft Edge',
use: {
...devices['Desktop Edge'],
channel: 'msedge'
},
},
{
name: 'Google Chrome',
use: {
...devices['Desktop Chrome'],
channel: 'chrome'
},
},
],
});
Now test scripts can execute the tests on the browsers mentioned in the config file in non headless mode with recording, trace viewer option.

Happy Learning !! Happy Automation !! Happy Testing

Feel free to connect me any information/Questions on [email protected] & LinkedIn Profile

https://www.linkedin.com/in/santosh-kulkarni-ab571639/

Release Statement This article is reproduced at: https://dev.to/santosh_kulkarni_ffbde129/automation-using-playwright-and-typescript-and-javascript-493l?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3