gpt4 book ai didi

javascript - 错误 : getItem() method does not exist (Angular, 模拟 LocalStorage)

转载 作者:行者123 更新时间:2023-12-03 08:59:46 24 4
gpt4 key购买 nike

我抓取了一段代码来模拟本地存储,但是,当我运行测试时,它抛出了这个错误。正如它所说,它找不到 getItem 方法,但我在 beforeEach block 之外显式声明了该方法。我不知道是什么引发了这个错误 - 希望得到提示和建议!

这是我的文件:

ma​​inCtrl.spec.js

describe('Controller: MainCtrl', function () {
var store = {};
var ls = function() {
return JSON.parse(store.storage);
};
var localStorage = {};

var getItem = function(key) {
return store[key];
}

var setItem = function(key, value) {
store[key] = value;
}

beforeEach(function() {
// setUp.
module('mytodoApp');

// LocalStorage mock.
spyOn(localStorage, 'getItem').andCallFake(getItem); <-- throwing the error
Object.defineProperty(sessionStorage, "setItem", { writable: true });
spyOn(localStorage, 'setItem').andCallFake(setItem);
});

afterEach(function() {
store = {};
});

var MainCtrl,
scope;

// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
MainCtrl = $controller('MainCtrl', {
$scope: scope
});
}));

it('should have no items to start with', function() {
// expect(scope.todos.length).toBe(0);
expect(Object.keys(store).length).toBe(0);
});
});

ma​​inCtrl.js

angular.module('mytodoApp')
.controller('MainCtrl', function ($scope, localStorageService) {
// breaks on repeat or blank input
function addTodoFn() {
$scope.todos.push($scope.todo);
$scope.todo = '';
}

function removeTodoFn(index) {
$scope.todos.splice(index, 1);
}

function watchFn() {
localStorageService.set('todos', $scope.todos);
}

//////////

var todosInStore = localStorageService.get('todos');
$scope.todos = todosInStore || [];
$scope.$watch('todos', watchFn, true);
$scope.addTodo = addTodoFn;
$scope.removeTodo = removeTodoFn;
});

编辑

var localStorage = { 
getItem: function(key) {
return store[key];
},

setItem: function(key, value) {
store[key] = value;
}
};

beforeEach(function() {
// setUp.
module('mytodoApp');

// LocalStorage mock.
spyOn(localStorage, 'getItem').andCallFake(getItem);
Object.defineProperty(sessionStorage, 'setItem', { writable: true });
spyOn(localStorage, 'setItem').andCallFake(setItem);
});

我按照@CosmicChild的建议进行了更改,但没有效果。

新错误消息

ReferenceError: Can't find variable: getItem

最佳答案

您需要在要 stub 的 localStorage 对象中定义一个空方法,

var localStorage = {
getItem: function(key) {
},
setItem: function(key, value) {
}
};

关于javascript - 错误 : getItem() method does not exist (Angular, 模拟 LocalStorage),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32347696/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com