量角器 - 空本地存储

teo*_*one 23 local-storage protractor

我正在使用Protractor(使用Jasmine)来测试我的AngulaJs应用程序.

由于我的一些操作,我得到了一些保存在localStorage中的数据.现在我需要测试其他情况,所以我需要清空我的存储空间(或者更好地删除一些项目)但是如果我尝试运行:

browser.executeScript('localStorage.removeItem("config");');
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

UnknownError: <unknown>: Failed to read the 'localStorage' property from 'Window': Storage is disabled inside 'data:' URLs.
  (Session info: chrome=35.0.1916.153)
  (Driver info: chromedriver=2.10.267517,platform=Mac OS X 10.9.2 x86_64)
Run Code Online (Sandbox Code Playgroud)

关于如何解决的任何想法?

提前致谢

Ant*_*zzo 37

另一个可能的解决方案是将任何状态清除放在afterEach中,它将在任何测试运行后运行:(参见https://github.com/angular/protractor/issues/188)

afterEach(function() {
    browser.executeScript('window.sessionStorage.clear();');
    browser.executeScript('window.localStorage.clear();');
});
Run Code Online (Sandbox Code Playgroud)

  • 确保在完成测试之前在浏览器中点击页面,否则您会在Chrome浏览器上遇到此问题.有关详细信息,请参阅http://stackoverflow.com/questions/21259235/remove-an-item-from-localstorage-in-a-protractor-test. (10认同)
  • `无法从'Window'读取'sessionStorage'属性:在'data:'URL.中禁用存储 (6认同)
  • 谢谢,这解释了为什么在使用phantomJS在beforeEach中使用它时它不起作用 (2认同)

Jed*_*rds 15

这是因为您还没有导航到有效的网址.browser.get('/foo')在尝试与页面对象交互之前做一个localStorage.


zay*_*uan 5

我通过尝试清除/修改sessionStorage或localStorage之前检查window.location解决了此问题。

如果尚未加载页面,则window.location.hostname等于空字符串''。因此,如果您得到空字符串,请不要尝试与sessionStorage或进行交互localStorage

这是我在量角器套件中使用的一些(ES6)代码,以防止出现此错误。请注意,这是一个Cucumber-js After函数,但是它仍然是使用chrome从量角器执行的,它演示了如何避免该错误:

this.After(function(scenario) {

  function getWindowLocation() {
    return window.location;
  }

  function clearStorage() {
    window.sessionStorage.clear();
    window.localStorage.clear();
  }

  return browser.executeScript(getWindowLocation).then(function(location) {
    // NB If no page is loaded in the scneario then calling clearStorage will cause exception
    // so guard against this by checking hostname (If no page loaded then hostname == '')
    if (location.hostname.length > 0) {
      return browser.executeScript(clearStorage);
    }
    else {
      return Promise.resolve();
    }
  });
});
Run Code Online (Sandbox Code Playgroud)


teo*_*one 3

我还没有找到一个很酷的方法来做到这一点,但如果我运行我的声明

 browser.executeScript("localStorage.removeItem('config');")
Run Code Online (Sandbox Code Playgroud)

在 it('description') 语句中它可以工作。例子:

it('should compile and save base config for billing',function(){
    browser.executeScript("localStorage.removeItem('config');")

    //my test
});
Run Code Online (Sandbox Code Playgroud)

这会删除名为 config 的项目,因此我的测试有效,但是在搜索和讨论此问题时,我得到的主要响应是:

“localStorage 不是你的产品,所以你不需要(阅读:你不能)测试它。正确的方法是模拟它并在需要时注入它的内容”

我仍在研究这个问题以了解如何实现,同时我认为哲学上不完美的测试仍然比没有好,所以......

希望这可以帮助...

  • 这是在真实浏览器上进行的功能测试,因此您必须与真实的 localStorage 进行交互。“localStorage 不是您的产品”答案仅适用于单元测试。 (2认同)