【问题标题】:What is done(), and where is it documented?什么是 done(),它记录在哪里?
【发布时间】:2019-12-23 18:09:34
【问题描述】:

我正在使用 Mocha/Sinon/Chai 了解 JavaScript 中的单元测试。我已经看到使用的函数done()。但我似乎找不到此功能的文档。它似乎不是 JavaScript 语言的一部分。如果是这样,我希望在 [something].prototype.done() 下的 Mozilla 文档中看到它。但它不存在。我没有在 jQuery 的文档中看到它,也没有在 Mocha 的文档中看到它。

On another thread,我看到done()这个例子:

it('should have data.', function () {
    db.put(collection, key, json_payload)
        .then(function (result) {
            result.should.exist;
            done();
        })
        .fail(function (err) {
            err.should.not.exist;
            done();
        })
})

什么是done(),它属于什么语言或工具,它的文档在哪里? done() 只是回调函数的命名约定吗?

【问题讨论】:

  • 看起来不对。是的,这是回调函数的命名约定……但缺少回调参数。 function (done) {?
  • 啊 - 我想我现在明白了。这是一个重复的问题然后 - stackoverflow.com/questions/28656780/… - 谢谢!
  • 并非如此。两人除了同名外,没有任何关系。例如,jQuery 在 jqXHR 上也有一个 done 方法。在您的情况下,因为您使用的是mocha,所以它与this 有关。继续阅读 db.put 使用的 Promise 用例。

标签: javascript unit-testing mocha.js sinon


【解决方案1】:

Done 是一个回调,mocha 将作为第一个参数提供给单元测试it block。在测试异步代码时通常需要它,因为可以调用它来通知 mocha it block 已完成。将回调命名为done 是一种很好的做法。但是,您可以根据需要为其命名。 您可以找到它的documentation here,只需在 Windows 上按 ctrl + f 或在 MAC 上按 + f,然后输入done

it('should have data.', function (done) { // inject done here
  db.put(collection, key, json_payload)
    .then(function (result) {
      result.should.exist;
      done();
    })
    .fail(function (err) {
      err.should.not.exist;
      done();
    })
})

从mocha网站复制以下内容。

Testing asynchronous code with Mocha could not be simpler! Simply invoke the callback when your test is complete. By adding a callback (usually named done) to it(), Mocha will know that it should wait for this function to be called to complete the test. This callback accepts both an Error instance (or subclass thereof) or a falsy value; anything else will cause a failed test

【讨论】:

  • 感谢您指出这一点 - 这很有趣。但是尊重,在阅读之后,我不确定done() 是“摩卡内置功能”,如你所说。看起来它是 Mocha 寻找的回调的命名约定(来自您的引用:“通常命名为完成”)。换句话说,Mocha 会寻找回调(“通常命名为 done”)。
  • @zumafra,同意
猜你喜欢
  • 2022-10-01
  • 1970-01-01
  • 2011-11-25
  • 2011-03-26
  • 1970-01-01
  • 2019-06-26
相关资源
最近更新 更多