簡體   English   中英

摩卡,nodejs承諾測試會因為缺少完成而無法完成

[英]Mocha, nodejs promise test can't finish because lack of done

我正在嘗試運行promise的測試,但是測試失敗,理由是它超過了超時限制,並建議確保我具有done子句。

這是我的測試代碼的一部分:

$configurations
    .updateConfiguration(configurations_driver.NOT_VALID_MODEL) //invalid model
    .then(function () {
        done(new Error("Expected INVALID_MODEL error but got OK"));
    }, function (error) {
        chai.assert.isNotNull(error);
        chai.expect(error.message).to.be.eq("INVALID_MODEL_ERROR");
        chai.expect(error.kind).to.be.eq("ERROR_KIND");
        chai.expect(error.path).to.be.eq("ERROR_PATH");
        done();
    })
    .catch(done);
});  

如您所見,我在其中擁有所有完成的子句,所以我不知道我是否在測試中遺漏了某些東西,或者結構只是錯誤的。

Mocha支持測試承諾,只要您return承諾就無需使用done

const expect = chai.expect

it('should error', function(){
  return $configurations
    .updateConfiguration(configurations_driver.NOT_VALID_MODEL) //invalid model
    .then(()=> { throw new Error("Expected INVALID_MODEL error but got OK")})
    .catch(error => {
      expect(error).to.not.be.null;
      expect(error.message).to.equal("INVALID_MODEL_ERROR");
      expect(error.kind).to.equal("ERROR_KIND");
      expect(error.path).to.equal("ERROR_PATH");
    })
})

還要查看chai-as-promised ,使承諾測試更像標准的chai斷言/期望。

chai.should()
chai.use(require('chai-as-promised'))

it('should error', function(){
  return $configurations
    .updateConfiguration(configurations_driver.NOT_VALID_MODEL)
    .should.be.rejectedWith(/INVALID_MODEL_ERROR/)
})

在Node 7.6+環境或具有babel / babel注冊的環境中,您還可以使用async / await承諾處理程序

it('should error', async function(){
  try {
    await $configurations.updateConfiguration(configurations_driver.NOT_VALID_MODEL)
    throw new Error("Expected INVALID_MODEL error but got OK")})
  } catch (error) {
    expect(error).to.not.be.null;
    expect(error.message).to.equal("INVALID_MODEL_ERROR");
    expect(error.kind).to.equal("ERROR_KIND");
    expect(error.path).to.equal("ERROR_PATH");
  }
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM