Are sinon.js spys catching errors?

So, I use mocha with chai to run my front tests, but I'm starting to turn on the sine and really love it. Except that the errors during the testing of the tests do not work, as shown by the synonymic documents.

Basically, I have 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 am 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 I'm trying to check also seems to stop the test from running

error message

I would suggest that sinon.spy would include some try / catch logic inside, spy.throw would not seem just as useful without it.

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

Am I doing something wrong?

+4
source share
3 answers

I think that one thing you could try is a statement against a spy object, not a method, to assign it to a variable. I don’t know how Sinon deals with all this magic of exception ... I think that it can work as you 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(); }); 

If this still does not work, I think you can also run this test with the standard chai if necessary, leaving the sine from the equation and actually getting a 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/); }); 

Or more briefly:

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

In your expectations, you mix the syntax of chai and sinon. Try

 expect(factory.create.threw()).to.be.ok(); 
0
source

Sometimes you want to check if functions that you don’t directly test were selected, i.e. error method to call ajax.

This approach worked for me:

 errorStub = sinon.stub(jQuery, "ajax").yieldsTo("error"); try { triggerError(); // triggers ajax call which yields to an error } expect(errorStub.threw()).to.be.true 
0
source

Source: https://habr.com/ru/post/1501744/


All Articles