I'm using Webdriver.io/Nodejs/Mocha and when I try to switch from parent tab to child tab, majority of the time it works; however, there are times that the tab will take a long time to load due to issues/bad adverts on the page and during those times, even though I get the window/tab GUID, it still doesn't switch and remains on the parent tab. It doesn't happen all the time but occassionally it fails to switch.
Does the page fully have to load to be able to switch to the chid tab? Am I missing anything? Any help would be appreciated. Thanks!
Execution:
npx mocha --config ./mocharc.json ./test/test.js
Test File: test.js
it('Test Case: Switch Tabs', async () => {
let parentGUID;
let childGUID;
// get parent GUID
parentGUID = await this.driver.getWindowHandle();
// click element to launch new tab
await this.driver.elementClick('//a[@id="test"]');
// wait until new tab loads
await this.driver.pause(2000);
// get all GUID's
const allGUIDs = await this.driver.getWindowHandles();
// check all GUID's and see which one is the child
for (let i = 0; i < allGUIDs.length; i++) {
if (allGUIDs[i] !== parentGUID) {
childGUID = allGUIDs[i];
}
}
// switch to child tab
await this.driver.switchToWindow(childGUID);
// assert content on the new page here
// ...
// ...
// ...
// close tab
await this.driver.closeWindow();
// switch to parent window/tab
await this.driver.switchToWindow(parentGUID);
}
This seems like a simple coding mistake. While you are initiating your parentGUID, you are not assigning any value to it. You are then using it to compare in your for loop. Sometimes, the childGUID is assigned with parent GUID. In this case, the switch seems to be not happening. I have corrected it below.
it('Test Case: Switch Tabs', async () => {
let childGUID;
// get parent GUID
const parentGUID = await this.driver.getWindowHandle();
// click element to launch new tab
await this.driver.elementClick('//a[@id="test"]');
// wait until new tab loads
await this.driver.pause(2000);
// get all GUID's
const allGUIDs = await this.driver.getWindowHandles();
// check all GUID's and see which one is the child
for (let i = 0; i < allGUIDs.length; i++) {
if (allGUIDs[i] !== parentGUID) {
childGUID = allGUIDs[i];
}
}
// switch to child tab
await this.driver.switchToWindow(childGUID);
// assert content on the new page here
// ...
// ...
// ...
// close tab
await this.driver.closeWindow();
// switch to parent window/tab
await this.driver.switchToWindow(parentGUID);
}