Search code examples
javascriptmocha.jschaiend-to-endnightwatch.js

Async test with nightwatch and mocha runner


I am trying to define few tests using nightwatch.js and mocha runner. I want to test how my javascript library works across different browsers.

My code is fairly simple and looks like that

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

describe('InfinitiSpec', function() {

  beforeEach((client, done) => {
    client.url(`file://${__dirname}/../../dist/index.html`);
    done();
  });

  after((client, done) => {
    client.end(() => done());
  });

  it('should be five', (client) => {
    client.execute(function() {
      // test javascript here
    }, [], () => {
      expect(2 + 2).to.equal(5)
    });
  });
});

The problem I have is that nightwatch does not pass done callback to the tests, therefore even trough if single test assertion fails test itself is still looks like it's successful.

vladmiller:infiniti-tracking-evolution vladmiller$ nightwatch 


  InfinitiSpec
 ✖ AssertionError: expected 4 to equal 5
    at Object.<anonymous> (/Users/vladmiller/Projects/xxx/xxx/test/browser/infiniti.spec.js:18:24)
    at HttpRequest.<anonymous> (/usr/local/lib/node_modules/nightwatch/lib/index.js:322:20)
    at emitTwo (events.js:87:13)
    at HttpRequest.emit (events.js:172:7)
    at HttpRequest.<anonymous> (/usr/local/lib/node_modules/nightwatch/lib/index.js:351:15)
    at emitThree (events.js:97:13)
    at HttpRequest.emit (events.js:175:7)
    at IncomingMessage.<anonymous> (/usr/local/lib/node_modules/nightwatch/lib/http/request.js:155:16)
    at emitNone (events.js:72:20)
    at IncomingMessage.emit (events.js:166:7)
    ✓ should be five (3322ms)


  1 passing (3s)

How can I test async javascript using nightwatch + mocha + chai? Also maybe one can recommend better stack for testing JS in selenium? Thanks


Solution

  • Nightwatch uses a patched version of mocha that doesn't support async tests. The solution is to use standard mocha instead, but the related documentation (http://nightwatchjs.org/guide#using-the-standard-mocha) is incomplete, and you'll have troubles getting access to page objects in that context.

    After spending one hour trying to setup Nightwatch with standard mocha, I decided to go back to plain Selenium Webdriver. And honestly, I don't regret it.

    If you want advice on how to do Nightwatch-like Page objects with just Selenium, check out http://marmelab.com/blog/2016/04/19/e2e-testing-with-node-and-es6.html