user1207289 user1207289 - 3 months ago 15
Node.js Question

mocha assertions passed before page loads

The below mocha and webdriverio script is passing assertions before the page loads.

I am not understanding how is it passing everything when probably the elements itself are not yet present. After page loads, I could see that the element is not clicked. Is that a fake pass? How do I fix that in code?

var webdriverio = require('webdriverio');
var should = require('chai').should()
var expect = require('chai').expect()
var options = {
desiredCapabilities: {
browserName: 'chrome'
}
};

before(function() {

browser=webdriverio.remote(options)
return browser.init()

});


describe('sauce labs page test', function() {
it('should assert page title', function(done) {




browser.url('https://docs.saucelabs.com/reference/platforms-configurator/?_ga=1.5883444.608313.1428365147#/');
browser.getTitle().then(function(title){
title.should.equal('Platform Configurator');
});
done();
});



it('should assert sub heading', function(done) {

browser.getText('h3').then(function(text) {
text.should.equal('API');
console.log(text);
});
done();
});


it('should click on selenium', function(done) {

browser.click('#main-content > div > ng-view > div > div:nth-child(1) > div.choice-buttons.choice-api > div:nth-child(2)')


done();
});


});

Answer

You should call the done callback inside the .then() handler, otherwise it's called before the browser has had a chance to load the page:

it('should assert page title', function(done) {
  browser.url('https://docs.saucelabs.com/reference/platforms-configurator/?_ga=1.5883444.608313.1428365147#/');
  browser.getTitle().then(function(title) {
    title.should.equal('Platform Configurator');
    done();
  });
});

However, this introduces another problem: if the assertion fails, done will never get called (because the exception is thrown before it).

Instead, you can use the fact that Mocha has built-in promises support. Instead of using the done callback, return a promise and Mocha will handle it (and any exceptions) properly:

it('should assert page title', function() {
  browser.url('https://docs.saucelabs.com/reference/platforms-configurator/?_ga=1.5883444.608313.1428365147#/');
  return browser.getTitle().then(function(title) {
    title.should.equal('Platform Configurator');
  });
});
Comments