Mocha / Chai期待。没有抓住抛出的错误 [英] Mocha / Chai expect.to.throw not catching thrown errors

查看:147
本文介绍了Mocha / Chai期待。没有抓住抛出的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到问题让Chai的 expect.to.throw 在我的node.js应用程序的测试中工作。测试在抛出错误时保持失败,但是如果我在try中包装测试用例并捕获并断言捕获的错误,则它可以工作。

I'm having issues getting Chai's expect.to.throw to work in a test for my node.js app. The test keeps failing on the thrown error, but If I wrap the test case in try and catch and assert on the caught error, it works.

expect.to.throw 不能像我想的那样工作吗?

Does expect.to.throw not work like I think it should or something?

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.


推荐答案

您必须将函数传递给期望。像这样:

You have to pass a function to expect. Like this:

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.'));

你这样做,你传递给期望调用 model.get('z')结果。但是为了测试是否抛出某些东西,你必须将一个函数传递给 expect expect 将调用它自己。上面使用的 bind 方法创建了一个新函数,调用时将使用调用 model.get 设置为 model 的值,第一个参数设置为'z'

The way you are doing it, you are passing to expect the result of calling model.get('z'). But to test whether something is thrown, you have to pass a function to expect, which expect will call itself. The bind method used above creates a new function which when called will call model.get with this set to the value of model and the first argument set to 'z'.

可以找到 bind 的一个很好的解释 here

A good explanation of bind can be found here.

这篇关于Mocha / Chai期待。没有抓住抛出的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆