【问题标题】:mocha assertions passed before page loadsmocha 断言在页面加载之前传递
【发布时间】:2016-08-08 16:25:43
【问题描述】:

下面的 mocha 和 webdriverio 脚本在页面加载之前传递断言。

当元素本身可能还不存在时,我不明白它是如何传递所有内容的。页面加载后,我可以看到该元素没有被点击。是假通行证吗?如何在代码中解决这个问题?

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();
});


 });

【问题讨论】:

    标签: javascript node.js mocha.js chai webdriver-io


    【解决方案1】:

    您应该在.then() 处理程序中调用done 回调,否则在浏览器有机会加载页面之前调用它:

    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();
      });
    });
    

    但是,这引入了另一个问题:如果断言失败,done 将永远不会被调用(因为在它之前会抛出异常)。

    相反,您可以使用 Mocha 内置的 Promise 支持这一事实。不要使用done 回调,而是返回一个promise,Mocha 会正确处理它(以及任何异常):

    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');
      });
    });
    

    【讨论】:

    • 谢谢。那行得通。我将使用承诺,但据我所知,done() 是如何知道它必须等到一个元素出现,在该元素上可以调用browser.getTitle(),最终可以调用title.should.equal('Platform Configurator'),所以一切都对齐。这么多隐藏的部分,很难理解
    • 您正在测试的代码是异步的,因此与任何异步代码一样,您必须等待异步操作完成才能继续(通过调用done,这向 Mocha 发出信号测试完成)。使用 Promise,当调用 then/onFullfilled 回调(或者,如果你有一个,catch/onRejected 回调)时,异步操作已经完成。
    猜你喜欢
    • 2021-05-10
    • 1970-01-01
    • 2014-07-21
    • 1970-01-01
    • 1970-01-01
    • 2017-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多