【问题标题】:Mocha, nodejs promise test can't finish because lack of doneMocha,nodejs promise 测试无法完成,因为没有完成
【发布时间】:2017-10-21 12:59:34
【问题描述】:

我正在尝试运行 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);
});  

如你所见,我有所有的 done 子句,所以我不知道是我在测试中遗漏了什么还是结构错误。

【问题讨论】:

    标签: javascript node.js mocha.js chai


    【解决方案1】:

    Mocha 支持在不使用 done 的情况下测试 Promise,只要您 return 承诺即可。

    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 以使 Promise 测试更像标准 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-register 的地方,您还可以使用 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");
      }
    })
    

    【讨论】:

      猜你喜欢
      • 2018-04-14
      • 2023-03-13
      • 2016-06-11
      • 2018-12-05
      • 1970-01-01
      • 2017-06-15
      • 2016-08-07
      • 1970-01-01
      • 2023-03-23
      相关资源
      最近更新 更多