在剧作家测试中切换标签

switch tabs in playwright test

我正在尝试使用剧作家测试在选项卡之间切换 但它没有控制 windows 元素。 剧作家里面有没有类似于selenium driver.switchto().window()的方法?

const { chromium } = require('playwright');
(async () => {
    const browser = await chromium.launch({ headless: false, args: ['--start-maximized'] });
    const context = await browser.newContext({ viewport: null });
    context.on("page", async newPage => {
        console.log("***newPage***", await newPage.title())
    })
    const page = await context.newPage()
    const navigationPromise = page.waitForNavigation()

    // dummy url
    await page.goto('https://www.myapp.com/')
    await navigationPromise

    // User login
    await page.waitForSelector('#username-in')
    await page.fill('#username-in', 'username')
    await page.fill('#password-in', 'password')
    await page.click('//button[contains(text(),"Sign In")]')
    await navigationPromise

    // User lands in application home page and clicks on link in dashboard 
    // link will open another application in new tab 
    await page.click('(//span[text()="launch-app-from-dashboard"])[2]')

    await navigationPromise
    await page.context()
    // Waiting for element to appear in new tab and click on ok button
    await page.waitForTimeout(6000)
    await page.waitForSelector('//bdi[text()="OK"]')
    await page.click('//bdi[text()="OK"]')

})()

假设"launch-app-from-dashboard"正在创建一个新的页面标签,您可以使用以下模式来运行新页面上的后续代码行。有关更多示例,请参阅 multi-page scenarios doc

// Get page after a specific action (e.g. clicking a link)
const [newPage] = await Promise.all([
  context.waitForEvent('page'),
  page.click('a[target="_blank"]') // Opens a new tab
])
await newPage.waitForLoadState();
console.log(await newPage.title());

因为你 运行 无头,使用 page.bringToFront (docs) 在浏览器中切换可见选项卡可能也很有用。

`it('Open a new tab and check the title', async function () {
    await page.click(button, { button: "middle" }); //to open an another tab
    await page.waitForTimeout(); // wait for page loading 
    let pages = await context.pages();
    expect(await pages[1].title()).equal('Title'); /to compare the title of the second page`

browserContext?.pages() 是一个数组,其中包含您的应用程序打开的选项卡,您可以从那里使用临时页面进行切换,完成验证后您可以切换回来。

playwright.pageMain: Page = await playwright.Context.newPage();
playwright.pageTemp: Page; 

// Save your current page to Temp 
playwright.pageTemp = playwright.pageMain;

// Make the new tab launched your main page
playwright.pageMain = playwright.browserContext?.pages()[1];
expect(await playwright.pageMain.title()).toBe('Tab Title');