【问题标题】:does mocha intelligently execute async code?mocha 是否智能地执行异步代码?
【发布时间】:2021-06-30 10:28:27
【问题描述】:

我有这个代码:

const mocha = require("mocha");
const assert = require("assert");


describe("saving records", function (done) {
 
  it("Saves a record to the database", function (done) {
    
    let mx = false;

    setTimeout(() => {
      mx = false; //#### note this line
    }, 6000);
    done();

    assert(mx === true);
  });
});

我不知道为什么,但是 mocha 在终端中给出了一个测试通过,上面写着:

保存记录 ✓ 将记录保存到数据库
1 次通过(30 毫秒)

问题一:为什么此时测试通过了

下一个奇怪的事情是: 在测试通过之前它甚至没有等待 6 秒。因为,我使用了done 参数,问题号。 2:不应该等到执行完成吗?

我是否误解了some information?

【问题讨论】:

    标签: node.js mocha.js


    【解决方案1】:
    const mocha = require("mocha");
    const assert = require("assert");
    
    describe("saving records", function (done) {
      it("Saves a record to the database", function (done) {
        let mx = false;
    
        setTimeout(() => {
          mx = false; //#### note this line
          assert(mx === true);
          done();
        }, 6000);
      });
    });
    

    在您的变体测试中通过,因为assertdone() 之后; 使用描述的异步测试here

    【讨论】:

    • 似乎有 2 秒的默认等待 done() 到达,我们可以增加这个吗?那么,在上述情况下,测试不会持续 6 秒,2 秒后就会超时,我们如何增加呢?
    • 超时可以是任何值,但您应该为测试设置最大值。请参阅此处的文档mochajs.org/#timeouts。在代码中使用 this.timeout(ms); 或在命令中使用 mocha --timeout 5000。也很好回答stackoverflow.com/questions/23492043/…
    猜你喜欢
    • 2019-02-26
    • 2019-08-27
    • 2017-09-25
    • 2018-01-25
    • 2019-01-28
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    相关资源
    最近更新 更多