gpt4 book ai didi

angularjs - 如何使用 Jasmine 和 Karma 模拟 angularjs $window.sessionStorage

转载 作者:行者123 更新时间:2023-12-02 20:30:12 27 4
gpt4 key购买 nike

我是 Jasmine 的新手,并试图弄清楚在使用 Jasmine 测试 angularjs SPA 时如何模拟 $window.sessionStorage 对象。

(function() {                            
'use strict';

var serviceId = 'session';

// Define the service on the module.
// Inject the dependencies.
// Point to the service definition function.
angular.module('app').service(serviceId, ['$window', session]);

function session($window) {

var token = null;

var service = {
create: create,
destroy: destroy,
getToken: getToken,
read: read
};

return service;

...

/**
* Get the session token
*/
function getToken() {
return this.token;
}

/**
* Read session variables from local session storage
*/
function read() {
this.token = $window.sessionStorage.getItem('token');
}
}
})();

我想做的一个简单测试就是删除 sessionStorage 并注入(inject)我的 stub 以进行测试。

'use strict';

describe("session", function() {
var session;
var $window;
beforeEach(module("app"));
/*
beforeEach(function() {
$window = {sessionStorage: {replace: jasmine.createSpy()}};

module(function($provide) {
$provide.value('$window', $window);
});
});
*/
beforeEach(inject(function (_session_) {
session = _session_;
}));

describe("read", function() {
it("should read session data from the window", function() {
$window.sessionStorage.token = 'token';
session.read();

expect(session.getToken()).toBe('token');
});
});
});

最佳答案

您可以简单地创建一个普通对象来实现您所需要的,如下所示:

describe("session", function() {

...

beforeEach(inject(function (_session_, _$window_) {
session = _session_;
$window = _$window_;

$window.sessionStorage = { // mocking sessionStorage
getItem: function(key) {
return this[key];
}
};
}));

...
});

关于angularjs - 如何使用 Jasmine 和 Karma 模拟 angularjs $window.sessionStorage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23391272/

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