代码之家  ›  专栏  ›  技术社区  ›  Suresh Prajapati

在用mocha测试asyc/await时使用done()的正确方法

  •  3
  • Suresh Prajapati  · 技术社区  · 7 年前

    我正在练习基本单元测试用例 mocha 有点困惑 使用 done() 处理程序。

    1. done() ?

    done :

    it('Testing insertDocumentWithIndex', async (done) => {
      try{
        var data = await db.insertDocumentWithIndex('inspections', {
          "inspectorId" : 1,
          "curStatus" : 1,
          "lastUpdatedTS" : 1535222623216,
          "entryTS" : 1535222623216,
          "venueTypeId" : 1,
          "location" : [
            45.5891279,
            -45.0446183
          ]
        })
        expect(data.result.n).to.equal(1);
        expect(data.result.ok).to.equal(1);
      }
      catch(e){
        logger.error(e);
        done(e);
      }
    })
    

    错误:超过了2000ms的超时时间。对于异步测试和挂钩,请确保 调用“done()”;如果你还了一个承诺,就要确保它能解决。

    但是 完成 应该只在失败的情况下调用(如果我说的不正确,请原谅我,我是一个初学者),这是我在 catch

    it('Testing insertDocumentWithIndex', async () => {
      return new Promise(async (resolve, reject) => {
        try{
          var data = await db.insertDocumentWithIndex('inspections', {
            "inspectorId" : 1,
            "curStatus" : 1,
            "lastUpdatedTS" : 1535222623216,
            "entryTS" : 1535222623216,
            "venueTypeId" : 1,
            "location" : [
              45.5891279,
              -45.0446183
            ]
          })
          expect(data.result.n).to.equal(1);
          expect(data.result.ok).to.equal(1);
          resolve()
        }
        catch(e){
          reject(e);
        }
      })
    });
    

    但这需要一个额外的Promise构造代码,它是反模式的。但这又提出了另一个问题

    1. 什么时候 应该用什么?

    有没有什么帮助或建议可以更好地编写测试用例 摩卡 会有帮助的。

    1 回复  |  直到 5 年前
        1
  •  8
  •   Estus Flask    5 年前

    正确的方法是不要使用 done 具有 async..await . 摩卡支持承诺,并能够连锁承诺,是返回的 it 等功能。以及 async 函数是始终返回承诺的函数的语法糖:

    it('Testing insertDocumentWithIndex', async () => {
        var data = await db.insertDocumentWithIndex('inspections', {
          "inspectorId" : 1,
          "curStatus" : 1,
          "lastUpdatedTS" : 1535222623216,
          "entryTS" : 1535222623216,
          "venueTypeId" : 1,
          "location" : [
            45.5891279,
            -45.0446183
          ]
        })
        expect(data.result.n).to.equal(1);
        expect(data.result.ok).to.equal(1);
    })
    

    完成

    还有这个

    it('Testing insertDocumentWithIndex', async () => {
      return new Promise(async (resolve, reject) => {
      ...
    

    是承诺构造反模式,因为 承诺构造函数回调。

    这些问题也适用于其他具有类似API、Jest和Jasmine的JS测试框架。

    推荐文章