I’m writing a test where I force an exception, and then call the same function in the catch block.
In my test, I need to spy on localStorage.setItem one time, which is where I simulate the exception. When the caller gets called again, I need to either remove the spy or somehow prevent the catch block from being hit again.
it('handles quota_exceeded exceptions', function() {
spyOn(localStorage, 'setItem').andCallFake(function() {
throw new Error("QUOTA_EXCEEDED_ERR", "QUOTA_EXCEEDED_ERR: DOM Exception 22");
});
spyOn(Obj, 'add').andCallThrough();
spyOn(Obj, 'clean');
expect(function() {
Obj.add('foo', 'bar');
}).not.toThrow();
expect(Garage.add.callCount).toBe(2);
});
The test code above produces an infinite loop, as the localStorage.setItem sets off an exception every time.
Any ideas or alternate testing patterns would be appreciated.
Thanks
You could store the localStorage quota status at a local variable. Something like: