在剧作家测试中切换标签

我正在尝试使用 playwright 测试在选项卡之间切换,但它没有控制 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"]')


})()


倚天杖
浏览 154回答 4
4回答

慕桂英3389331

假设"launch-app-from-dashboard"正在创建一个新的页面标签,您可以使用以下模式在新页面上运行后续代码行。// 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 )切换浏览器中的可见选项卡也可能很有用。

达令说

假设您只创建了一个页面(通过浏览器上下文),但由于某种原因,打开了新页面/选项卡。您可以通过 : 获得所有页面的列表context.pages,现在该列表的每个元素代表一个<class 'playwright.async_api._generated.Page'>对象。所以,现在您可以将每个页面分配给任何变量并访问它。(例如。page2 = context.pages[1])

冉冉说

browserContext?.pages() 是一个数组,其中包含您的应用程序打开的选项卡,您可以从那里使用临时页面进行切换,一旦完成验证,您就可以切换回来。playwright.pageMain: Page = await playwright.Context.newPage();playwright.pageTemp: Page;&nbsp;// Save your current page to Temp&nbsp;playwright.pageTemp = playwright.pageMain;// Make the new tab launched your main pageplaywright.pageMain = playwright.browserContext?.pages()[1];expect(await playwright.pageMain.title()).toBe('Tab Title');

元芳怎么了

it('Open a new tab and check the title', async function () {&nbsp; await page.click(button, { button: "middle" }); //to open an another tab&nbsp; await page.waitForTimeout(); // wait for page loading&nbsp;&nbsp; let pages = await context.pages();&nbsp; expect(await pages[1].title()).equal('Title'); /to compare the title of the second page})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript