Dennis Krupchenko
Dennis Krupchenko

Reputation: 19

Nightwatch - Do another action if the element is not present

How to write a simple if/else in NightwatchJS? If element is present, click this element, else - click another element.

'Test2: click login button': function(client) {

    client.expect.element('.login .btn').to.be.present;
    client.click('.login .btn');


//  if "client.expect.element('.login .btn') is not present(visible)" - 
//      but "client.expect.element('a.menu-link').to.be.present(visible)";
//  client.click('a.menu-link');


    client.pause(1000);
});

},

Upvotes: 0

Views: 2274

Answers (1)

zgreen
zgreen

Reputation: 4698

There may be more than one way to do this, but I'd use the Webdriver Protocol's .element() function:

'Test2: click login button': client => {
  const buttonSelector = '.login .btn';
  const menuLinkSelector = 'a.menu-link';
  client.element('css selector', buttonSelector, result => {
    if (result.status > -1) {
      // `.login .btn` is present
      client.click(buttonSelector);
    } else {
      // else, check for `a.menu-link`
      client.element('css selector', menuLinkSelector, () => {
        client.click(menuLinkSelector);
      });
    }   
  });
  client.end();
}

Upvotes: 2

Related Questions