【问题标题】:Chai, testing that function throws correct errorChai,测试该功能会引发正确的错误
【发布时间】:2015-08-28 20:51:16
【问题描述】:

基本上,我正在练习使用 Mocha 进行测试,并且我编写了一个模式,其中序列号应该是唯一的。我想要一个测试,表明当我再次尝试使用该序列号时,它会为重复键引发 Mongo 错误 E11000。

phaseSchema.statics.createPhase = function(name,sernum,desc){
  var phase = mongoose.model('phases', phaseSchema)
  var newphase = new phase({NAME: name, SERNUM: sernum,DESC: desc});
  newphase.save(function(err,newphase){
      if(err)
        return console.error(err);
  })
}

我尝试了很多不同的方法,但我得到超时错误或断言被忽略,我无法弄清楚。

我觉得我最接近的是

it("throws error when non unique sequence number is used", function(done){    
    (function () {
        ucdphase.createPhase('d0','develop',0,"desc")
    }).should.throw("E11000 duplicate key error index: test.ucdphase.$");

    done();
  });

但是接下来发生的事情是将错误打印到控制台然后说

"AssertionError: expected [Function] to throw an error.

【问题讨论】:

    标签: javascript mongodb unit-testing mongoose mocha.js


    【解决方案1】:

    根据chai documentation,您应该使用expect 开始断言。

    另外我认为你不需要使用done 回调。该回调用于测试异步代码。

    试试这个:

    it("throws error when non unique sequence number is used", function(){    
        expect(function () {
            ucdphase.createPhase('d0','develop',0,"desc")
        }).to.throw("E11000 duplicate key error index: test.ucdphase.$");
      });
    

    【讨论】:

    • 我现在一次又一次地尝试过,它给了我 AssertionError: expected{ Object (__flags) } to be a function
    • 对不起,我犯了一个错误,现在已修复示例:should 替换为 to
    • @Angie 我仍然遇到同样的错误。你是怎么解决的?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-25
    • 2020-01-05
    • 1970-01-01
    • 2017-11-14
    • 2020-08-01
    • 1970-01-01
    • 2019-09-07
    相关资源
    最近更新 更多