Search code examples
node.jsseleniummocha.jsassert

Return promise from assert inside 'then'


I need to make a sequence of selenium commands using 'then' but I don't know how to return a promise from asserts in this case. I keep getting this warning:

(node:18772) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): AssertionError [ERR_ASSERTION]: 'League of Legends' == 'Dota 2 on Reddit'

(node:18772) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Example of what I'm saying:

var assert = require('assert');
var webdriver = require('selenium-webdriver');

it('should do something with promises', function(done) {
  this.timeout(300000);
  driver = new webdriver.Builder().
  withCapabilities(webdriver.Capabilities.firefox()).
  build();
  driver.get("https://www.reddit.com/r/leagueoflegends/").
  then( () => driver.getTitle()).
  then( (title) => assert.equal(title,"Dota 2 on Reddit")).
  then(() => driver.quit()).
  then(() => done());
});

Solution

  • You're getting an error somewhere along the line and it's not being handled anywhere. A quick easy fix would be to add

    .catch(e => done(e))
    

    to the end of your last .then(...). This will catch any error from any of the .then(...)s and you can handle it appropriately. Mocha considers a test failing if you call done() and pass it any parameter, like done(e). Failing that you can always invoke assert.fail like this.

    .catch(e => assert.fail(e, 'expected value', 'Unknown description here'))