摩卡最好的方法来抛出错误并测试

时间:2015-08-11 23:04:57

标签: javascript mocha chai

我想确保只允许整数作为参数,所以我写了这个测试。

describe('Assigning values', function () {
  it('Should only be able to assign integers', function () {
    var item = new Item();

    expect(item.setValue('string').to.throw(Error, 'Not an integer'));
  });
});

我正在测试的功能

  var testInteger = function(num) {
    if (typeof num === 'number' && (num % 1 ) === 0) {
      return;
    } else {
      throw new Error('Not an integer');
    }
  };

从setValue调用testInteger。

此测试失败,我不确定应该如何编写。

1 个答案:

答案 0 :(得分:3)

to.throw期望函数作为参数,即传递要测试的函数,而不是函数调用的 result 。这样可以确保在expect中实际触发该方法,并抛出异常。

example in the Chai documentation很好,它只是在匿名函数中包装要测试的函数(在本例中为throw err;):

var fn = function () { throw err; }
expect(fn).to.throw(Error);

所以你可以试试:

expect(function(){ item.setValue('string'); }).to.throw(Error, 'Not an integer');

另请注意我所做的更改,即测试中的函数直接传递到expect,然后to.throw被链接(括号的位置)。