如何正确模拟此方法的返回值?

时间:2019-05-31 12:00:08

标签: jestjs

我正在尝试模拟.getItem()方法的返回值,但控制台显示“ localStorage.getItem.mockReturnValueOnce不是函数”而出错。听起来像语法错误?有人可以指出以下问题吗?

// target file
const getKey = () => {
  return localStorage.getItem('someKey')
};


// test file
const localStorageMock = {
  getItem : jest.fn()
};

global.localStorage = localStorageMock;


test('getKey', () => {  
  localStorage.getItem.mockReturnValueOnce(3);

  expect(targetFile.getKey()).toEqual(3);
});

也尝试过:

注释localStorageMock()并改为使用:

test('getResultMarker', () => {
  global.localStorage.getItem = () => 3;         

  expect(targetFile.getResultMarker('resultMarker')).toEqual(3); // returns null
});

提供jest.fn()回调:

global.localStorage.getItem = jest.fn(() => 3); 
// expect(...).toEqual(...) returns null as before

当我尝试记录回调的值时,出现错误消息“期望的1个参数,得到0”。然后执行以下操作,我再次得到null:

console.log(global.localStorage.getItem(1), 
`=====localStorage.getItem()=====`); // null

完全重新分配该属性以尝试覆盖Storage对象:

global.localStorage = {
  getItem : jest.fn(() => 3)
};

console.log(global.localStorage.getItem(1), 
`=====localStorage.getItem()=====`);  
console.log(global.localStorage, `=====global.localStorage=====`);


// console
null '=====global.localStorage.getItem()====='

Storage {} '=====global.localStorage====='

您可以看到Storage对象仍然存在。我认为这是问题所在。有人知道如何覆盖它吗?

0 个答案:

没有答案