5

So, I'm using mocha with chai to do my front-end testing, but I'm starting to incorporate sinon and really liking it. Except that testing throwing errors isn't working quite how the sinon docs seem to indicate.

Basically, I've got this method:

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;
},

and I'm testing it with this expectation:

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

    factory.create();

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

    factory.create.restore();
});

however, the error, which I'm try to test for, also seems to halt the execution of the test

error message

I'd thought sinon.spy would include some try / catch logic internally, spy.throw doesn't seem as useful without it.

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

Am I doing something wrong??

4

3 回答 3

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();
});

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

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

或更简洁地说:

it('throws error if missing second argument', function() {
  expect(factory.create).to.throw(/unsupported collection type/);
});
于 2013-10-07T06:03:18.267 回答
0

在您的期望中,您混合了 chai 和 sinon 语法。尝试

expect(factory.create.threw()).to.be.ok();
于 2013-09-14T19:33:54.450 回答
-1

有时你想检查一个你没有直接测试的函数是否抛出了错误,即errorajax调用的方法。

这种方法对我很有效:

errorStub = sinon.stub(jQuery, "ajax").yieldsTo("error");

try {
  triggerError();  // triggers ajax call which yields to an error
}

expect(errorStub.threw()).to.be.true
于 2014-11-06T20:53:43.263 回答