【问题标题】:Mocha Before Hook not working asynchronouslyMocha Before Hook 不能异步工作
【发布时间】:2017-10-27 04:37:08
【问题描述】:

我似乎无法让 before 钩子异步。

我使用了before 钩子来启动它,它确实如此,但我试图在它失败时接起,这样我就可以失败/跳过整个块(因为没有服务器可以测试)。

我在整个代码中都使用了 [async] before 挂钩,但在这种情况下,它不会等待我的 done 被触发。

基本上,得到了一堆 MochaJS 测试,对于一个块,我需要启动一个 Web 服务器,以便我可以向它发出请求以测试 RESTful API。我想确保它成功启动,因此是异步方法。

describe('RESTful Tests', function(){
    // Start up the whole express server for these API tests
    before(function(done) {
        try {
            server.on('error', (e) => {
                console.error("HERE");
                done();
            });

            listener = server.listen(port, function() {
                console.log("Server Started");
                done();
            });
            console.error("AFTER LISTEN");

        } catch(err) {
            console.error("ON Caught");
            done();
        }
        console.error("At End!!");
    });

这会运行,并在测试中显示为1) "before all" hook,但它不会等待调用done。我只是得到输出...

    RESTful Tests
AFTER LISTEN
At End!!
    1) "before all" hook

其他项目均未显示,但我会收到关于 EADDRINUSE 的异常(预计因为我已阻止端口)。我真的很难找到一种方法来解决这个问题。

我知道它在不同的(有点)“线程”中,所以我不会发现错误,但仍然...... 为什么不遵守异步 done 方法? em>

【问题讨论】:

    标签: express asynchronous mocha.js


    【解决方案1】:

    似乎有些文档有点误导......

    Node/ExpressJS 文档状态将.on('error' 方法放在server 对象上。在这种情况下,它似乎需要在 listener 对象上!

    所以我的最终 [工作] 代码看起来像这样......

    listener = server.listen(port, function() { 
        done();
    }).on('error', (function(e) {
        this.skip(e.code);
        done();
    }).bind(this));
    

    耶!!! :)

    【讨论】:

      猜你喜欢
      • 2019-10-14
      • 2013-11-23
      • 1970-01-01
      • 2017-12-28
      • 2021-04-18
      • 1970-01-01
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      相关资源
      最近更新 更多