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 badges
Add a ment  | 

1 Answer 1

Reset to default 7

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

本文标签: javascriptHow to spy on localStorage methods with jasmineStack Overflow