elnuggs
elnuggs

Reputation: 121

Go to page URL using test.BeforeAll for playwright-test runner

test.beforeAll(async ({ page }) => {
   // Go to the starting url before each test.
   await page.goto('https://my.start.url/');
 });

Is there a nice way in playwright-test runner to setup the browser and navigate to the page related to the page object to run the tests in that file?

I want to avoid doing this "test.beforeEach" for everyone if possible. Currently its not possible to do this in playwright-test but it is possible in jest. Any ideas?

Property 'page' does not exist on type 'PlaywrightWorkerArgs & PlaywrightWorkerOptions'.

Upvotes: 12

Views: 27957

Answers (3)

aoki ken
aoki ken

Reputation: 116

// example.spec.ts

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

test.describe.configure({ mode: 'serial' });

let page: Page;

test.beforeAll(async ({ browser }) => {
  // Create page once and sign in.
  page = await browser.newPage();
  await page.goto('https://github.com/login');
  await page.locator('input[name="user"]').fill('user');
  await page.locator('input[name="password"]').fill('password');
  await page.locator('text=Sign in').click();
});

test.afterAll(async () => {
  await page.close();
});

test('first test', async () => {
  // page is signed in.
});

test('second test', async () => {
  // page is signed in.
});

https://playwright.dev/docs/test-auth#reuse-the-signed-in-page-in-multiple-tests

Upvotes: 9

SudoGrace
SudoGrace

Reputation: 169

As said above (by Leon), you can create your own page, but to avoid creating a new page for each test (Joaquin Casco asked about it), just don't pass page as a parameter to your test function.

I mean:

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

test.beforeAll(async () => {
    const browser = await chromium.launch();
    const page = await browser.newPage();

    // Go to the starting url before each test.
    await page.goto('https://my.start.url/');
});

// Will create a new page instance
test('Test with page as parameter', async ({ page }) => {}) 

// Does not create new page, so you can use the page from beforeAll hook (if you bring it into the scope)
test('Test without page as parameter', async () => {}) 

Upvotes: 14

Leon
Leon

Reputation: 717

You could create a page by yourself:

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

test.beforeAll(async () => {
    const browser = await chromium.launch();
    const page = await browser.newPage();

    // Go to the starting url before each test.
    await page.goto('https://my.start.url/');
});

You need install the playwright package.

Upvotes: 3

Related Questions