Nightwatch.js: Open new window and continue testing in new window

Using Nightwatch.js, let’s say you have a button that opens a new window, and you want to do some testing in that new window, such as checking the new window’s url.

  // open new window button
 .verify.visible('.open-new-window')
 .getAttribute('.open-new-window', 'href', function (link) {
 newWindowUrl = link.value;
 })
 .click('.open-new-window')
 .windowHandles(function(result) {
    var newWindow;
    this.verify.equal(result.value.length, 2, 'There should be 2 windows   open');
    newWindow = result.value[1];
    this.switchWindow(newWindow);
    this.verify.urlContains(newWindowUrl);
})

Notice the windowHandles() function that returns all the windows open in the session, and the switchWindow() function allows you to switch windows and target newWindow.  The context of “this” becomes the new window that you switched to.

One thought on “Nightwatch.js: Open new window and continue testing in new window”

  1. Hi, I´m new with nightwatch. I tried to follow your example but still doesn´t open the link. Can you help please? Thanks.

    var host = ‘http://m.unitel.ao/fit/’;
    module.exports = {
    “Facebook link” : function (browser) {
    browser
    .url(host)
    .waitForElementVisible(‘.socal’, 3000)
    .waitForElementPresent(‘.fa.fa-facebook’, 2000)
    // open new window button
    .verify.visible(‘a[href=”https://www.facebook.com/unitel.ao/?fref=ts”]’)
    .getAttribute(‘a[href=”https://www.facebook.com/unitel.ao/?fref=ts”]’, ‘https://www.facebook.com/unitel.ao/?fref=ts’, function (link) {
    newWindowUrl = link.value;
    })
    .click(‘a[href=”https://www.facebook.com/unitel.ao/?fref=ts”]’)
    .windowHandles(function(result) {
    var newWindow;
    this.verify.equal(result.value.length, 2, ‘There should be 2 windows open’);
    newWindow = result.value[1];
    this.switchWindow(newWindow);
    this.verify.urlContains(newWindowUrl);
    })
    .assert.urlContains(‘facebook’)
    .end();
    }
    };

Leave a Reply

Your email address will not be published. Required fields are marked *