【问题标题】:How does Mocha know to be async? [duplicate]Mocha 怎么知道是异步的? [复制]
【发布时间】:2016-01-24 21:05:33
【问题描述】:

Mocha 可以确定是否需要回调 (done),或者是否应该同步运行测试,这完全取决于您将回调作为参数传递。

// Sync
it("should be amazing", function (){
    expect(amazing).equals(true);
});

// Async
it("should be amazing, eventually", function (done) {
  setTimeout(function () {
    expect(amazing).equals(true);
    done();
  }, 1000);
});

我不知道它是怎么做到的。我能想到的唯一方法是,它实际上将函数解析为字符串,将其分解并确定是否传递了参数。

这是怎么回事?

【问题讨论】:

标签: javascript function mocha.js


【解决方案1】:

你不会想到它,但函数有一个length 属性!它等于函数接受的参数数量。

当我找到它时,我将编辑答案以从 mocha 中添加一个 sn-p,但这是一种可以检测它是否接受参数的有效方法。检查长度是否为 1,这决定了测试是否是异步的。

编辑: I found it. 对于上下文,it 继承自 Runnable

function Runnable(title, fn) {
    // Other properties...
    this.async = fn && fn.length;
    // Other properties...
}

【讨论】:

    【解决方案2】:

    它在回调中使用字符串解析器或参数长度检查。

    类似的东西

    function it(name, callback) {
    
       if (callback.length > 0) {
          callback(function done(e) {
              if (e) throw "test finished with error"
              //test finished
          })
    
       } else {
           callback()
           //test finished
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-11-14
      • 1970-01-01
      • 2021-10-05
      • 1970-01-01
      • 2011-07-30
      • 2018-05-23
      • 2021-06-10
      • 2019-07-06
      • 2012-04-18
      相关资源
      最近更新 更多