【问题标题】:How to make the "it" in mocha to wait until the promise within "it" gets resolved?如何让 mocha 中的“它”等到“它”中的承诺得到解决?
【发布时间】:2018-01-10 18:21:45
【问题描述】:
var promise = require('promise');
var {Builder, By, Key, until} = require('selenium-webdriver');
var test = require('selenium-webdriver/testing');
var chai = require('chai');
var getUrl = require('./wdio.conf.js');
var driver = new Builder().forBrowser('chrome').build();

test.describe('Proper Testing', function() {
    test.it('should prompt the server from user', function() {
        return new promise(function(resolve,reject){
            resolve(driver.get("https://www.google.co.in"));
            reject(err);
        })
    })
}) 

对于上面给出的代码,运行 mocha proper.js 会在 chrome 浏览器中打开给定的 url,但测试失败并出现超时错误。 我读过如果测试返回一个承诺,就不需要调用 done() 。 给定的代码有什么问题?

【问题讨论】:

    标签: javascript node.js selenium asynchronous mocha.js


    【解决方案1】:

    完成测试后,您必须致电done。

    我不确定你想在这里实现什么,但这个示例代码应该说明我的观点:

    describe('Proper Testing', function() {
    
        it('should prompt the server from user', function(done) {
            return getUrl().then(function(url){
                driver.get(url)
                .then(function () {
                  done();
                }).catch(function (err) {
                  done(err);
                });
            })
        });
    
    })
    

    参考:https://mochajs.org/#asynchronous-code

    【讨论】:

    • 不,done() 没有解决问题。脚本仍然会导致错误并且不等待用户响应提示。
    【解决方案2】:

    关于您的问题,尝试添加一个设置高超时的 before 语句。普通测试有一个默认的超时时间(我觉得是2秒),如果测试超过这个时间,就会报错,测试不通过。

    before(function (done) {
        this.timeout(5000);
        done();
    })
    

    关于done:如果你要返回一个promise,你不需要使用done。简单地声明 function() 不带任何参数,如果它没有引发任何异常并且它完成所有断言它发现它通过了测试。

    describe('Proper Testing', function() {
    
        it('should prompt the server from user', function() {
            return getUrl().then(function(url){
                driver.get(url);
            })
        });
    
    })
    

    【讨论】:

    • 我为“它”添加了 20 秒的超时时间,以便用户可以响应提示和 console.log 来验证承诺是否得到解决。控制台语句记录了正确的 url,因此 getUrl() 中的承诺确实得到了解决。 driver.get(url) 也可以正常工作。现在当一切都执行时,为什么脚本会抛出同样的错误?
    • 您是否设置了以毫秒为单位的时间(20000)?您是否删除了 done 参数?
    • 是的,我确实删除了 done 参数并以毫秒为单位设置了超时。我对上面给出的原始代码进行了编辑。
    • 只是试一试,在 driver.get(url);返回 driver.get(url);
    猜你喜欢
    • 2020-10-17
    • 2021-02-02
    • 2016-03-19
    • 1970-01-01
    • 2017-05-25
    • 2019-09-23
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多