user3142695 user3142695 -3 years ago 70
Javascript Question

How to test if navigation menu has all expected items?

I am using Nightwatch.js (Selenium/WebDriver) to test my Node.js application.

Now I would like to test if a navigation bar is existing and I also want to test if the items of the navbar are as expected.

This is how I tried to get all navigation items, but I don't know how to check the elements. Also I think this is a bit too complicated. Is this the correct way to use Nightwatch.js?

module.exports = {
'navigation': function(browser) {
var navElements = []

function getNavElements(elements) {
elements.value.forEach(function(element) {
browser.elementIdText(element.ELEMENT, function(res) {
navElements.push(res.value)
})
})
}

browser
.url(browser.launchUrl)
.waitForElementVisible('#nav', 10000)

browser.expect.element('#nav').to.be.present

browser.elements('css selector', '#nav > .item', getNavElements)
browser.expect(navElements).to.equal(['First', 'Second', 'Third'])

browser.end()
}
}

Answer Source

Your code is almost correct, but this is what you missed:

  • getNavElements is a callback, so you cannot be sure that navElements will be populated as expected when you test it on the next line.
  • browser.expect is not a function. It is a simple object containing an element method. If you want to perform a regular test with expect, you will have to use Chai directly (Nightwatch BDD-style interface is based on this library).

Here is a minimal working code:

HTML (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Nightwatch</title>
</head>
<body>
  <ul id="nav">
    <li class="item">First</li>
    <li class="item">Second</li>
    <li class="item">Third</li>
  </ul>
</body>
</html>

JavaScript (nav.js)

var expect = require('chai').expect;

module.exports = {
  'Navigation': function (browser) {
    var expectedNavElements = ['First', 'Second', 'Third'];

    function testNavElements(elements) {
      elements.value.forEach(function (element, index) {
        browser.elementIdText(element.ELEMENT, function(res) {
          expect(res.value).to.equal(expectedNavElements[index]);
        });
      });
    }

    browser
      .url('http://localhost:8000/index.html') // Change this if needed
      .waitForElementVisible('#nav', 1000);

    browser.expect.element('#nav').to.be.present;
    browser.elements('css selector', '#nav > .item', testNavElements);

    browser.end();
  }
};

Commands

  1. npm i chai to install Chai
  2. nightwatch -t tests/nav.js to run the test suite

Note: If Chai expectations pass, you will not get any message in console because this is not handled by Nightwatch natively. But if they do not pass, you will get an assertion error. Try to put wrong values in expectedNavElements and you will see...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download