Test new window url using protractor

You can test the new window url using protractor.


Consider a scenario where you have to click on a html element(say <a href='url' target='_blank'/>) which opens a new window and you want to check the url of the new window opened using protractor. You can check the url using below code

it("should check the new window url"function () {
    element(by.id('id of the element to be clicked')).click();
    browser.getAllWindowHandles().then(function (handles) {
        newWindowHandle = handles[1];
        browser.switchTo().window(newWindowHandle).then(function () {
            expect(browser.driver.getCurrentUrl()).toBe("url to check");
        });
    });
});

The above code checks the url of the new window opened.

Note:

In the above code we are using browser.driver.getCurrentUrl() because the newly opened window may not contain angular in it. If it conatins angular, then use browser.getCurrentUrl() to get the url of the window.

Now if you want to close the newly opened window and test something else on the previous window you can do that by using below code 

it("should check the new window url"function () {
    element(by.id('id of the element to be clicked')).click();
    browser.getAllWindowHandles().then(function (handles) {
        newWindowHandle = handles[1];
        browser.switchTo().window(newWindowHandle).then(function () {
            expect(browser.driver.getCurrentUrl()).toBe("url to check");
            //to close the current window
            browser.driver.close().then(function () {
                //to switch to the previous window
                browser.switchTo().window(handles[0]);
            });
 
        });
    });
});

The above code closes the newly opened window after the url is checked and switches to the previous window.

In this way you can check the url of the new window using protractor.

For more posts on protractor visit: Protractor

No comments:

Post a Comment