不要sinon.js spys捕获错误?

noT*_*Txt 5 javascript unit-testing mocha.js sinon

所以,我正在使用mocha与chai进行前端测试,但我开始整合sinon并且非常喜欢它.除了测试抛出错误并不能解决sinon文档似乎表明的问题.

基本上,我有这个方法:

create: function(bitString, collectionType) {
    var collection;

    switch(collectionType) {
        case 'minutesOfHour':
            collection = this.createMinutesOfHour(bitString);
            break;

        case 'hoursOfDay':
            collection = this.createHoursOfDay(bitString);
            break;

        case 'daysOfWeek':
            collection = this.createDaysOfWeek(bitString);
            break;

        case 'daysOfMonth':
            collection = this.createDaysOfMonth(bitString);
            break;

        case 'monthsOfYear':
            collection = this.createMonthsOfYear(bitString);
            break;

        default:
            throw new Error('unsupported collection type ' + collectionType);
    }

    return collection;
},
Run Code Online (Sandbox Code Playgroud)

我正在用这个期望来测试它:

it('throws error if missing second arguement', function() {
    sinon.spy(factory, 'create');

    factory.create();

    expect(factory.create).to.have.thrown();

    factory.create.restore();
});
Run Code Online (Sandbox Code Playgroud)

但是,我试图测试的错误似乎也停止了测试的执行

错误信息

我认为sinon.spy会在内部包含一些try/catch逻辑,spy.如果没有它,它似乎没有用.

http://sinonjs.org/docs/#spies

难道我做错了什么??

nac*_*son 4

我认为您可以尝试的一件事是针对间谍对象而不是方法进行断言,将其分配给变量。不太知道 sinon 如何处理所有这些异常魔法......我认为它可能会像你预期的那样工作。

it('throws error if missing second argument', function() {
  var spy = sinon.spy(factory, 'create');

  factory.create();

  expect(spy).to.have.thrown();

  factory.create.restore();
});
Run Code Online (Sandbox Code Playgroud)

如果这仍然不起作用,我认为如果需要的话,您也可以使用标准 chai 进行此测试,将 sinon 排除在等式之外,并实际检查错误是否具有正确的消息。

it('throws error if missing second argument', function() {
  expect(function() {
    factory.create();
  }).to.throw(/unsupported collection type/);
});
Run Code Online (Sandbox Code Playgroud)

或者更简洁地说:

it('throws error if missing second argument', function() {
  expect(factory.create).to.throw(/unsupported collection type/);
});
Run Code Online (Sandbox Code Playgroud)