Don't sinon.js spys catch errors?
因此,我正在使用带有chai的mocha进行前端测试,但是我开始结合使用sinon并非常喜欢它。除了测试抛出错误无法正常工作以外,sinon文档似乎指示了这种情况。
基本上,我有这个方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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; }, |
并且我正在以这种期望对其进行测试:
1 2 3 4 5 6 7 8 9 | it('throws error if missing second arguement', function() { sinon.spy(factory, 'create'); factory.create(); expect(factory.create).to.have.thrown(); factory.create.restore(); }); |
但是,我试图测试的错误似乎也停止了测试的执行
我以为sinon.spy内部会包含一些try / catch逻辑,spy.throw似乎没有它有用。
http://sinonjs.org/docs/#spies
我做错什么了吗?
我认为您可以尝试针对间谍对象而不是方法断言,将其分配给变量。我真的不知道sinon如何处理所有这些异常魔术...我认为它可能像您期望的那样工作。
1 2 3 4 5 6 7 8 9 | 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排除在等式之外,然后实际检查错误是否具有正确的消息。
1 2 3 4 5 | it('throws error if missing second argument', function() { expect(function() { factory.create(); }).to.throw(/unsupported collection type/); }); |
或更简洁:
1 2 3 | it('throws error if missing second argument', function() { expect(factory.create).to.throw(/unsupported collection type/); }); |
在您的期望中,您混合使用了chai和sinon语法。试试
1 | expect(factory.create.threw()).to.be.ok(); |
有时候您想检查一下您是否在未直接测试的函数上抛出了错误,即ajax调用的
这种方法对我有效:
1 2 3 4 5 6 7 | errorStub = sinon.stub(jQuery,"ajax").yieldsTo("error"); try { triggerError(); // triggers ajax call which yields to an error } expect(errorStub.threw()).to.be.true |