使用 test.BeforeAll 转到剧作家测试运行程序的页面 URL

eln*_*ggs 8 javascript playwright

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

playwright-test runner 中有没有一种很好的方法来设置浏览器并导航到与页面对象相关的页面以运行该文件中的测试?

如果可能的话,我想避免为每个人做这个“test.beforeEach”。目前在剧作家测试中不可能做到这一点,但在开玩笑中是可能的。有任何想法吗?

Property 'page' does not exist on type 'PlaywrightWorkerArgs & PlaywrightWorkerOptions'.
Run Code Online (Sandbox Code Playgroud)

小智 11

正如上面(Leon)所说,您可以创建自己的页面,但为了避免为每个测试创建一个新页面(Joaquin Casco 询问过),请不要将页面作为参数传递给测试函数。

我是说:

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 () => {}) 
Run Code Online (Sandbox Code Playgroud)

  • 这会阻止您在 chromium 之外运行测试吗? (5认同)

小智 7

// 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.
});
Run Code Online (Sandbox Code Playgroud)

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


Leo*_*eon 3

您可以page自己创建一个:

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/');
});
Run Code Online (Sandbox Code Playgroud)

您需要安装该playwright软件包。