Mocha / Chai expect.to.throw 不捕获抛出的错误

2022-08-29 23:57:26

我在让 Chai's 为我的节点.js应用的测试中工作时遇到了问题。测试在引发的错误上不断失败,但是如果我将测试用例包装在尝试并捕获并断言捕获的错误中,则它可以正常工作。expect.to.throw

不像我认为的那样工作或什么?expect.to.throw

it('should throw an error if you try to get an undefined property', function (done) {
  var params = { a: 'test', b: 'test', c: 'test' };
  var model = new TestModel(MOCK_REQUEST, params);

  // neither of these work
  expect(model.get('z')).to.throw('Property does not exist in model schema.');
  expect(model.get('z')).to.throw(new Error('Property does not exist in model schema.'));

  // this works
  try { 
    model.get('z'); 
  }
  catch(err) {
    expect(err).to.eql(new Error('Property does not exist in model schema.'));
  }

  done();
});

失败:

19 passing (25ms)
  1 failing

  1) Model Base should throw an error if you try to get an undefined property:
     Error: Property does not exist in model schema.

答案 1

您必须将函数传递给 。喜欢这个:expect

expect(model.get.bind(model, 'z')).to.throw('Property does not exist in model schema.');
expect(model.get.bind(model, 'z')).to.throw(new Error('Property does not exist in model schema.'));

按照您这样做的方式,您将传递到调用的结果。但是要测试是否抛出某些内容,您必须将函数传递给 ,该函数将调用自身。上面使用的方法创建一个新函数,当调用该函数时,将调用设置为 的值,并将第一个参数设置为 。expectmodel.get('z')expectexpectbindmodel.getthismodel'z'

一个很好的解释可以在这里找到。bind


答案 2

正如这个答案所说,你也可以把你的代码包装在一个匿名函数中,就像这样:

expect(function(){
    model.get('z');
}).to.throw('Property does not exist in model schema.');