admin管理员组文章数量:1310193
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.
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.
Share Improve this question asked May 10, 2018 at 11:47 MumzeeMumzee 8081 gold badge13 silver badges29 bronze badges1 Answer
Reset to default 7As 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
本文标签: javascriptHow to spy on localStorage methods with jasmineStack Overflow
版权声明:本文标题:javascript - How to spy on localStorage methods with jasmine - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741808676a2398661.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论