简体   繁体   English

摩卡,nodejs承诺测试会因为缺少完成而无法完成

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

I'm trying to run the test of a promise, but the test fails arguing it exceeded timeout limit, and suggests to make sure I have the done clauses. 我正在尝试运行promise的测试,但是测试失败,理由是它超过了超时限制,并建议确保我具有done子句。

This is part of my test code: 这是我的测试代码的一部分:

$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);
});  

I have all the done clauses in there as you can see, so I don't know if I'm missing something in the test or the structure is just wrong. 如您所见,我在其中拥有所有完成的子句,所以我不知道我是否在测试中遗漏了某些东西,或者结构只是错误的。

Mocha supports testing promises without using done as long as you return the promise. 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");
    })
})

Also look at chai-as-promised to make promise testing more like standard chai assertions/expectations. 还要查看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/)
})

On Node 7.6+ environments or where you have babel / babel-register you can also make use of the async / await promise handlers 在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