我们如何对 Angular 中的会话存储进行单元测试?

Pra*_*dau 1 unit-testing karma-jasmine angular

我是 Angular 单元测试的新手,我正在尝试测试会话存储和本地存储。

我的代码是:

subscribe(data) {
        sessionStorage.setItem('myProductDetail', JSON.stringify(data));
    }

subscribe(data) {
        LocalStorage.setItem('dummyname', data[0].name);
    }
Run Code Online (Sandbox Code Playgroud)

对会话、本地存储和私有类进行单元测试是一个好习惯吗?

我尝试按照下面的示例代码来模拟我的本地存储和会话存储。

beforeEach(function () {
  var store = {};

  spyOn(localStorage, 'getItem').andCallFake(function (key) {
    return store[key];
  });
  spyOn(sessionStorage, 'setItem').andCallFake(function (key, value) {
    return store[key] = value + '';
  });
  spyOn(localStorage, 'clear').andCallFake(function () {
      store = {};
  });
});
Run Code Online (Sandbox Code Playgroud)

非常感谢任何指导。

ain*_*cat 6

有关浏览器差异的更多详细信息,请参阅线程https://github.com/jasmine/jasmine/issues/299 。

方法0:

保持原样。Firefox 或 phantomjs 将设置存储,之后您可以检查存储中的值。如果您仍然需要自定义反应,您可以在部分中监视它beforeEach

方法一:直接监视sessionStorage
可以与 phantomjs 一起使用,并且可能是 chrome,但不能在 FF 中使用。

const store = {};
spyOn(sessionStorage, 'getItem').and.callFake((key) => {
  return store[key];
});
spyOn(sessionStorage, 'setItem').and.callFake((key, value) => {
  console.log(key);
  return store[key] = value + '';
});
Run Code Online (Sandbox Code Playgroud)

方法二:更换sessionStorage.
可以在 firefox 中工作,但不能在 phantomjs 中工作,因为它禁止sessionStorage替换。但 phantomjs 允许监视它,因此方法 1 可以工作。

const mock = (() => {
  let store = {};
  return {
    getItem: (key) => {
      return store[key];
    },
    setItem: (key, value) => {
      console.log(key);
      store[key] = value + '';
    },
    clear: () => {
      store = {};
    }
  };
})();
Object.defineProperty(window, 'sessionStorage', { value: mock, writable: true });
Run Code Online (Sandbox Code Playgroud)

方法三:窥探Storage.prototype
将适用于所有实施,但替换所有存储。

spyOn(Storage.prototype, 'setItem').and.callFake((key, value) => {
  console.log(key);
  // some logic like in prev examples
});
// other spyOn
Run Code Online (Sandbox Code Playgroud)

您可以将方法 1 和方法 2 结合起来,就像本文作者对上一个版本所做的那样https://blog.bradleygore.com/2014/09/17/angular-unit-testing-pt-1-local-storage/