摩卡/柴的Expect.to.throw不能捕获抛出的错误

我在让Chai的expect.to.thrownode.js应用程序进行测试时遇到问题测试会不断导致抛出的错误,但是如果我将测试用例包装在try和catch中并断言所捕获的错误,它将起作用。

难道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.
LPro2020/03/20 13:48:55

doc中的示例...;)

因为您依赖于此上下文

  • .throw调用函数时丢失的内容
  • 它没有办法知道这应该是什么

您必须使用以下选项之一:

  • 方法或函数调用包装在另一个函数中
  • 绑定上下文

    // wrap the method or function call inside of another function
    expect(function () { cat.meow(); }).to.throw();  // Function expression
    expect(() => cat.meow()).to.throw();             // ES6 arrow function
    
    // bind the context
    expect(cat.meow.bind(cat)).to.throw();           // Bind