Skip to main content

externalBrowseTheWebWithPlaywright

This implementation of the ability to BrowseTheWeb enables the Actor to interact with web front-ends using Playwright.

Using Playwright to BrowseTheWeb

In the example below, we configure the ability to BrowseTheWebWithPlaywright with a Playwright Browser so that Serenity/JS actors can create a new BrowserContext and instantiate Playwright pages as and when needed.

This configuration allows Serenity/JS to control the process of launching and shutting down browser instances and is useful when your test runner, e.g. Cucumber.js, doesn't offer this functionality.

import { actorCalled } from '@serenity-js/core'
import { BrowseTheWebWithPlaywright } from '@serenity-js/playwright'
import { By, Navigate, PageElement, Text } from '@serenity-js/web'
import { Ensure, equals } from '@serenity-js/assertions'
import { Browser, chromium } from 'playwright'

const HomePage = {
title: () =>
PageElement.located(By.css('h1')).describedAs('title')
}

const browser = await chromium.launch({ headless: true });

await actorCalled('Wendy')
.whoCan(BrowseTheWebWithPlaywright.using(browser))
.attemptsTo(
Navigate.to(`https://serenity-js.org`),
Ensure.that(Text.of(HomePage.title()), equals('Serenity/JS')),
)

Using BrowseTheWeb with an existing Playwright page

Test runners like Playwright Test manage Playwright browsers for you and offer a page instance you can inject into the ability to BrowseTheWebWithPlaywright.

Note that Serenity/JS Playwright Test module automatically configures all your actors with an ability to BrowseTheWebWithPlaywright, so you don't need to do it by hand unless you want to override the default configuration.

The example below demonstrates how to use the BrowseTheWebWithPlaywright.usingPage API and override the default cast of actors.

import { describe, it, test } from '@playwright/playwright-test'
import { BrowseTheWebWithPlaywright } from '@serenity-js/playwright'
import { By, Navigate, PageElement, Text } from '@serenity-js/web'
import { Ensure, equals } from '@serenity-js/assertions'

const HomePage = {
title: () =>
PageElement.located(By.css('h1')).describedAs('title')
}

describe('Serenity/JS with Playwright', () => {

test.use({
actors: async ({ page, contextOptions }, use) => {
await use(
Cast.where((actorName: string) => {
return actor.whoCan(
BrowseTheWebWithPlaywright.usingPage(page),
// ... add any other abilities
)
})
)
}
})

it('lets you reuse an existing page', async ({ actor }) => {
await actor.attemptsTo(
Navigate.to(`https://serenity-js.org`),
Ensure.that(Text.of(HomePage.title()), equals('Serenity/JS')),
)
})
})

Configuring Playwright

If you're using Serenity/JS with Playwright Test, Serenity/JS will automatically pick up your configuration from the playwright.config.ts file.

With other test runners, you can configure Playwright by:

The code snippet below demonstrates how to configure the browser and some popular browser context options, such as viewport size, geolocation, and permissions, but you can use it to configure any other option available in Playwright, like userAgent or storageState.

import { actorCalled } from '@serenity-js/core'
import { BrowseTheWebWithPlaywright } from '@serenity-js/playwright'
import { Navigate } from '@serenity-js/web'
import { Browser, chromium } from 'playwright'

// specify browser launch options
const browser = await chromium.launch({
headless: true
});

await actorCalled('Wendy')
.whoCan(BrowseTheWebWithPlaywright.using(browser, {
// specify browser context options
viewport: { width: 1600, height: 1200 },
geolocation: { longitude: 51.50084271042897, latitude: -0.12462540129500639 },
permissions: [ 'geolocation' ],
}, {
defaultNavigationTimeout: 30_000,
defaultTimeout: 10_000
}))
.attemptsTo(
Navigate.to(`https://serenity-js.org`),
// ...
)

Note that in addition to all the standard Playwright BrowserContextOptions, you can also provide several others defined in Serenity/JS ExtraBrowserContextOptions, such as:

  • defaultNavigationTimeout, which changes the default maximum navigation timeout for the browser context,
  • defaultTimeout, which changes the default maximum time for all Playwright methods accepting the timeout option.

Learn more

Hierarchy

Implements

Index

Constructors

externalconstructor

Methods

staticexternalusing

staticexternalusingPage

staticexternalusingElectronApp

  • Creates an ability to browse the web using an already-launched Electron application.

    Use this method when the Electron application lifecycle is managed externally, such as in Playwright Test where the app is launched per-worker.

    Example

    import { _electron as electron } from 'playwright';
    import { actorCalled } from '@serenity-js/core';
    import { BrowseTheWebWithPlaywright } from '@serenity-js/playwright';

    const electronApp = await electron.launch({ args: ['main.js'] });

    const actor = actorCalled('Tester').whoCan(
    BrowseTheWebWithPlaywright.usingElectronApp(electronApp)
    );

    // After tests, close the app manually
    await electronApp.close();

    Parameters

    • externalelectronApp: ElectronApplication

      An already-launched Playwright ElectronApplication instance

    • externaloptionalextraBrowserContextOptions: ExtraBrowserContextOptions

      Optional configuration for timeouts and navigation

    Returns BrowseTheWebWithPlaywright

staticexternallaunchingElectronApp

  • launchingElectronApp(launchOptions: { acceptDownloads?: boolean; args?: string[]; artifactsDir?: string; bypassCSP?: boolean; chromiumSandbox?: boolean; colorScheme?: light | dark | no-preference; cwd?: string; env?: {}; executablePath?: string; extraHTTPHeaders?: {}; geolocation?: { latitude: number; longitude: number; accuracy?: number }; httpCredentials?: { username: string; password: string; origin?: string; send?: unauthorized | always }; ignoreHTTPSErrors?: boolean; locale?: string; offline?: boolean; recordHar?: { omitContent?: boolean; content?: omit | embed | attach; path: string; mode?: full | minimal; urlFilter?: string | RegExp }; recordVideo?: { dir?: string; size?: { width: number; height: number }; showActions?: { duration?: number; position?: top-left | top | top-right | bottom-left | bottom | bottom-right; fontSize?: number } }; timeout?: number; timezoneId?: string; tracesDir?: string }, extraBrowserContextOptions?: ExtraBrowserContextOptions): BrowseTheWebWithPlaywright
  • Creates an ability to browse the web by launching and managing an Electron application.

    Use this method when you want Serenity/JS to manage the Electron application lifecycle. The app is launched on first use and closed when the ability is discarded.

    Example

    import { actorCalled } from '@serenity-js/core';
    import { BrowseTheWebWithPlaywright } from '@serenity-js/playwright';

    const actor = actorCalled('Tester').whoCan(
    BrowseTheWebWithPlaywright.launchingElectronApp({
    args: ['path/to/main.js'],
    cwd: 'path/to/app',
    })
    );

    // The app is automatically closed when the actor is dismissed

    Parameters

    • externallaunchOptions: { acceptDownloads?: boolean; args?: string[]; artifactsDir?: string; bypassCSP?: boolean; chromiumSandbox?: boolean; colorScheme?: light | dark | no-preference; cwd?: string; env?: {}; executablePath?: string; extraHTTPHeaders?: {}; geolocation?: { latitude: number; longitude: number; accuracy?: number }; httpCredentials?: { username: string; password: string; origin?: string; send?: unauthorized | always }; ignoreHTTPSErrors?: boolean; locale?: string; offline?: boolean; recordHar?: { omitContent?: boolean; content?: omit | embed | attach; path: string; mode?: full | minimal; urlFilter?: string | RegExp }; recordVideo?: { dir?: string; size?: { width: number; height: number }; showActions?: { duration?: number; position?: top-left | top | top-right | bottom-left | bottom | bottom-right; fontSize?: number } }; timeout?: number; timezoneId?: string; tracesDir?: string }

      Options for launching the Electron application

      • externaloptionalacceptDownloads: boolean

        Whether to automatically download all the attachments. Defaults to true where all the downloads are accepted.

      • externaloptionalargs: string[]

        Additional arguments to pass to the application when launching. You typically pass the main script name here.

      • externaloptionalartifactsDir: string

        If specified, artifacts (traces, videos, downloads, HAR files, etc.) are saved into this directory. The directory is not cleaned up when the browser closes. If not specified, a temporary directory is used and cleaned up when the browser closes.

      • externaloptionalbypassCSP: boolean

        Toggles bypassing page's Content-Security-Policy. Defaults to false.

      • externaloptionalchromiumSandbox: boolean

        Enable Chromium sandboxing. Defaults to false.

      • externaloptionalcolorScheme: light | dark | no-preference

        Emulates prefers-colors-scheme media feature, supported values are 'light' and 'dark'. See page.emulateMedia([options]) for more details. Passing null resets emulation to system defaults. Defaults to 'light'.

      • externaloptionalcwd: string

        Current working directory to launch application from.

      • externaloptionalenv: {}

        Specifies environment variables that will be visible to Electron. Defaults to process.env.

      • externaloptionalexecutablePath: string

        Launches given Electron application. If not specified, launches the default Electron executable installed in this package, located at node_modules/.bin/electron.

      • externaloptionalextraHTTPHeaders: {}

        An object containing additional HTTP headers to be sent with every request. Defaults to none.

      • externaloptionalgeolocation: { latitude: number; longitude: number; accuracy?: number }
      • externaloptionalhttpCredentials: { username: string; password: string; origin?: string; send?: unauthorized | always }

        Credentials for HTTP authentication. If no origin is specified, the username and password are sent to any servers upon unauthorized responses.

      • externaloptionalignoreHTTPSErrors: boolean

        Whether to ignore HTTPS errors when sending network requests. Defaults to false.

      • externaloptionallocale: string

        Specify user locale, for example en-GB, de-DE, etc. Locale will affect navigator.language value, Accept-Language request header value as well as number and date formatting rules. Defaults to the system default locale. Learn more about emulation in our emulation guide.

      • externaloptionaloffline: boolean

        Whether to emulate network being offline. Defaults to false. Learn more about network emulation.

      • externaloptionalrecordHar: { omitContent?: boolean; content?: omit | embed | attach; path: string; mode?: full | minimal; urlFilter?: string | RegExp }

        Enables HAR recording for all pages into recordHar.path file. If not specified, the HAR is not recorded. Make sure to await browserContext.close([options]) for the HAR to be saved.

      • externaloptionalrecordVideo: { dir?: string; size?: { width: number; height: number }; showActions?: { duration?: number; position?: top-left | top | top-right | bottom-left | bottom | bottom-right; fontSize?: number } }

        Enables video recording for all pages into recordVideo.dir directory. If not specified videos are not recorded. Make sure to await browserContext.close([options]) for videos to be saved.

      • externaloptionaltimeout: number

        Maximum time in milliseconds to wait for the application to start. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.

      • externaloptionaltimezoneId: string

        Changes the timezone of the context. See ICU's metaZones.txt for a list of supported timezone IDs. Defaults to the system timezone.

      • externaloptionaltracesDir: string

        If specified, traces are saved into this directory.

    • externaloptionalextraBrowserContextOptions: ExtraBrowserContextOptions

      Optional configuration for timeouts and navigation

    Returns BrowseTheWebWithPlaywright

externaltoJSON

  • Returns a JSON representation of the ability and its current state, if available. The purpose of this method is to enable reporting the state of the ability in a human-readable format, rather than to serialise and deserialise the ability itself.


    Returns SerialisedAbility

externalabilityType

  • Returns the most abstract type of this Ability instance, specifically the first class in the inheritance hierarchy that directly extends the Ability class.

    import { Ability } from '@serenity-js/core';

    class MyAbility extends Ability {}
    class MySpecialisedAbility extends MyAbility {}

    new MyAbility().abilityType(); // returns MyAbility
    new MySpecialisedAbility().abilityType(); // returns MyAbility

    Returns AbilityType<Ability>

externalinitialise

  • initialise(): Promise<void>
  • Returns Promise<void>

externalisInitialised

  • isInitialised(): boolean
  • Returns boolean

externaldiscard

  • discard(): Promise<void>

externalcurrentPage

  • currentPage(): Promise<Page<Locator>>
  • Returns a Page representing the currently active browser tab.


    Returns Promise<Page<Locator>>

externalallPages

  • allPages(): Promise<Page<Locator>[]>
  • Returns an array of pages representing all the browser tabs available in the current BrowsingSession.


    Returns Promise<Page<Locator>[]>

externalbrowserCapabilities