Hi,
I'm just starting with Jasmine and I'm having a bit of a hard time understanding how throwError works.
In the official docs this is the sample code:
foo = {
setBar: function(value) {
bar = value;
}
spyOn(foo, "setBar").and.throwError("quux");
And then comes the expectation for the spec:
expect(function() {
foo.setBar(123)
}).toThrowError("quux");
What I can't seem to understand is, if the throwErrror is being added to the spy and then the setBar method is being called, When can we expect that the setBar method
is not going to throw an error "quux"?. As far as I can understand the setBar method
will always throw an error. I tried creating a method that actually throws an error if no arguments are passed, like this:
var foo = {
setBar: function(value) {
if(!value) {
throw "you must pass a value"
} else {
bar = value;
}
}
};
// then
it("Should throw error", function(){
spyOn(foo, "setBar").and.throwError("no value");
expect( function() {
foo.setBar()
}).toThrowError("no value");
});
I would expect the error
"you must pass a value", but it always throws the error passed in and.throwError().
As a follow up question, what's the point of testing an error that's already defined and will be returned everytime no matter what arguments we use in the function?.
I can't understand the need of this when there's already the toThrowError for a simple call:
var foo = {
setBar: function(value) {
if(!value) {
throw "you must pass a value"
} else {
bar = value;
}
}
};
it("Should throw error", function(){
expect( function() {
foo.setBar()
}).toThrowError("you must pass a value");
});
I'm pretty sure I'm missing something about spies, but after reading and reading I can't seem to find what.
Thanks,
Rodrigo.