【问题标题】:mocha on test fail cannot do asynchronous function测试失败的摩卡不能做异步功能
【发布时间】:2017-07-29 16:26:31
【问题描述】:

当测试失败时,我正在使用 mocha 的 runner.on("fail", postProcessFunction) 执行一些后期处理。

见:https://github.com/mochajs/mocha/blob/master/lib/runner.js#L58

我的问题是,在postProcessFunction 函数中,我需要调用一个函数slowFunction,它会创建一个文件并返回一个承诺。承诺需要 10 秒才能解决,到那时,mocha 已经进入下一个测试或完全停止执行。 slowFunction 函数没有完成执行并且文件永远不会被创建。

我尝试使用promise.then(something) 处理承诺,并将postProcessFunction 包装在Q.async 中,然后将yielding 包装到slowFunction,但我似乎永远无法让它等待慢速功能在继续之前完成。

注意:我不能使用全局 afterEach,因为测试已经具有套件级别 afterEach,它将在全局 afterEach 之前执行。我需要在失败时立即执行slowFunction

【问题讨论】:

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


    【解决方案1】:

    您可以在 afterEach 中检测到测试失败,这将允许您使用标准 mocha 异步设置。

    afterEach('Test failure debug', function(){
      debug('Test result', this.currentTest)
      if (this.currentTest.state === 'failed') {
        return page.source().then(src => debug('Page source', src))
      }
    })
    

    在这种特殊情况下,page 变量的作用域在 describe 块中,因此它在测试和 before/after 帮助程序中都可用。

    【讨论】:

    • 我已经考虑过这个解决方案,但我的测试已经有 afterEach 块。我希望在每次测试之后和任何其他 afterEach 之前执行此操作
    • 你可以使用 async/await
    猜你喜欢
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-24
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    相关资源
    最近更新 更多