如何在量角器测试中访问$ localStorage会产生WebDriverError

时间:2016-06-06 14:14:26

标签: javascript angularjs selenium selenium-webdriver protractor

我试图期望localStorage值,我认为可以从window对象访问。但每当我尝试运行以下代码时:

browser.executeScript(function () {
       console.log('window.localStorage:'+window.localStorage);
      });

我收到以下错误: - Java Process打开JVM执行,控制台显示:

node_modules/selenium-webdriver/error.js:26
  constructor(opt_error) {
                         ^
    WebDriverError: {"errorMessage":"SecurityError: DOM Exception 18","request":{"headers":{"Accept-Encoding":"gzip,deflate","Connection":"Keep-Alive","Content-Length":"135",
"Content-Type":"application/json; charset=utf-8","Host":"localhost:41937","User-Agent":"Apache-HttpClient/4.5.1 (Java/1.7.0_79)"},"httpVersion":"1.1","method":"POST","post":"{\"script\":\"return (function () {\\n   console.log('window.localStorage:'+window.localStorage);\\n  }).apply(null, arguments);\",\"args\":[]}","url":"/execute","urlParsed":{"anchor":"","query":"","file":"execute","directory":"/","path":"/execute","relative":"/execute","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/execute","queryKey":{},"chunks":["execute"]},"urlOriginal":"/session/2d7fbb70-2bf0-11e6-8379-b56f27de83cd/execute"}}
Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 17:00:58'
System info: host: 'home', ip: '192.168.0.10', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11.5', java.version: '1.7.0_79'
Driver info: driver.version: unknown
    at WebDriverError (/node_modules/selenium-webdriver/error.js:26:26)

2 个答案:

答案 0 :(得分:1)

要从本地存储中获取项目,请使用window.localStorage.getItem()executeScript()

var value = browser.executeScript("return window.localStorage.getItem('key');");
expect(value).toEqual(expectedValue);

为方便起见,我们还可以在本地存储周围安装此辅助对象/包装器:

"use strict";

var LocalStorage = function () {
    this.getValue = function (key) {
        return browser.executeScript("return window.localStorage.getItem('" + key + "');");
    };

    this.get = function () {
        browser.executeScript("return window.localStorage;");
    };

    this.clear = function () {
        browser.executeScript("return window.localStorage.clear();");
    };
};

module.exports = new LocalStorage();

答案 1 :(得分:0)

问题是您尝试使用代码打印storage类型的对象。

   console.log('window.localStorage:'+window.localStorage);     

相反,您可以使用的是PropertiesMethods,其中包含要显示相应存储类型的键。 e.g。

   console.log('window.localStorage.font:' + window.localStorage.getItem('font'));

有关存储属性和方法的详细信息为here in the document.