不要sinon.js spys捕获错误? [英] Don't sinon.js spys catch errors?

查看:92
本文介绍了不要sinon.js spys捕获错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

我做错了什么?

推荐答案

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

I think one thing you could try is asserting against a spy object instead of the method, assign it to a variable. Not really knowing how sinon deals with all this exception magic...I think it might just work as you had expected.

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

  factory.create();

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

  factory.create.restore();
});

如果仍然不起作用我想你也可以用标准的柴进行这个测试,将sinon排除在等式之外并实际获得错误具有正确消息的检查。

If that still doesn't work I think you could also do this test with standard chai if need be, leaving sinon out of the equation and actually gaining the check that the error has the correct message.

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

这篇关于不要sinon.js spys捕获错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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