Reputation: 61
In a web application (implemented in React), when I press a specific button, then a new browser tab is opened. I would like to check that this happened and if the URL of the new tab is correct.
Upvotes: 6
Views: 5558
Reputation: 9831
test('new tab', async ({ page, context }) => {
// init test....
const [newTab] = await Promise.all([
context.waitForEvent('page'),
page.click('a[target="_blank"]') // your new tab logic here...
]);
await expect(newTab.url()).toBe('http://test');
});
Upvotes: 1
Reputation: 3222
You could implement it like that
// @ts-check
const playwright = require("playwright");
(async () => {
const browser = await playwright.chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://example.org/');
// Important to "start" this promise before the window.open() could happen
const newPagePromise = new Promise(resolve => context.once("page", resolve))
// Imagine some internal window.open() logic
await page.evaluate(() => {
setTimeout(() => {
window.open("https://github.com/microsoft/playwright", "_blank")
}, 3 * 1000)
})
// Here we are waiting until the page has been opened
const newPage = await newPagePromise
// Since its a normal Page instance, we can now assert the URL of it
console.log(newPage.url(), await newPage.title())
await browser.close();
})();
See it here interactively on Try Playwright: https://try.playwright.tech/?s=g8vb1si
Upvotes: 2