Suppose I have a JavaScript code:
function modifiesLocalStorage() {
var someBoolean = false;
if(localStorage.getItem('someKey') === 'true'){
localStorage.removeItem('someKey');
someBoolean = true;
}
return someBoolean;
}
Then I have a jasmine test to test this method:
it('should return true', function(){
spyOn(localStorage, 'removeItem');
spyOn(localStorage, 'getItem').and.returnValue('true');
var returnValue = modifiesLocalStorage();
expect(localStorage.getItem).toHaveBeenCalled(); //Error in this line
expect(returnValue).toBeTruthy();
});
while executing this test I am getting following error:
Error: <toHaveBeenCalled> : Expected a spy, but got Function.
What is this error and how do I fix it?
I am using Firefox 45.9.0 browser in headless mode to run the tests.
As per this question's answer: Expected a spy, but got Function We need to get into the actual method, which in this case is on the proto.
if I modify my tests like below, the test passes:
it('should return true', function(){
spyOn(localStorage.__proto__, 'removeItem');
spyOn(localStorage.__proto__, 'getItem').and.returnValue('true');
var returnValue = modifiesLocalStorage();
expect(localStorage.__proto__.getItem).toHaveBeenCalled();
expect(returnValue).toBeTruthy();
});
Since __proto__
is deprecated we can also use Object.getPrototypeOf(localStorage)
to get the prototype of the localStorage
object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With