Thanks to Danyal Aytekin for his Stackoverflow answer. If you want to use the toThrow in Jasmin tests on actual functions, you can use the “Function.bind
, which was introduced in JavaScript 1.8.5. This works in the latest versions of Chrome and Firefox, and you can patch other browsers by defining the function yourself.”
From his answer:
describe('using bind with jasmine', function() {
var f = function(x) {
if(x === 2) {
throw new Error();
}
}
it('lets us avoid using an anonymous function', function() {
expect(f.bind(null, 2)).toThrow();
});
});
Thanks Danyal!
EDIT: An alternative to this is to use the try catch:
describe('with try catch', function() {
var f = function(x) {
if(x === 2) {
throw new Error();
}
}
it('lets us avoid using an anonymous function', function() {
try {
f(2);
// fail if we get here, the exception wasn't thrown
expect(false).toBeTruthy();
}
catch(){
expect(true).toBeTruthy();
});
});