量角器,无法从会话存储中获取正确的数据

时间:2018-06-18 12:46:08

标签: javascript protractor automated-tests session-storage

我是新的量角器,我需要从会话存储中获取数据,我需要检查字段的存在。我怎样才能做到这一点?我必须检查记录的用户是否具有“firstCode”字段的值。这是sessionStorage数据的一个例子:

{"bookCode":"CNMPPS","agency":"vu","topCode":"HHH4C","firstDate":"14042018","secondDate":"","firstCode":"ROM","secondCode":"ROM","carCode":"RM","market":"","lang":"en","customer":{"FieldNumber":"IKH8272HKS","title":"MR","firstName":"Mark","lastName":"Venium","email":"markvenium@hotmail.com","customerType":"","loyaltyTier":""}}

这是我的代码stepdefinitions.js

var j_userData = browser.driver.executeScript('sessionStorage.getItem("userData");');
var firstCode = JSON.parse(j_userData).firstCode;
expect(firstCode).to.not.be.null;

控制台将此返回给我:

SyntaxError: Unexpected token M in JSON at position 0
   at JSON.parse (<anonymous>)

有人可以帮我从sessionStorage中获取正确的字段值吗?谢谢。

2 个答案:

答案 0 :(得分:0)

sessionStorage只能存储字符串值。不确定如何使用上面的代码存储它,我从未使用过protactor,但你可以尝试在存储之前对数据进行字符串化。 我假设量角器具有相同的代码样式以便存储

  

存储

var jsonData = JSON.stringify({"bookCode":"CNMPPS","agency":"vu","topCode":"HHH4C","firstDate":"14042018","secondDate":"","firstCode":"ROM","secondCode":"ROM","carCode":"RM","market":"","lang":"en","customer":{"FieldNumber":"IKH8272HKS","title":"MR","firstName":"Mark","lastName":"Venium","email":"markvenium@hotmail.com","customerType":"","loyaltyTier":""}});
var j_userData = browser.driver.executeScript('sessionStorage.setItem("userData", ' + jsonData+ ' );');
  

接收

var j_userData = browser.driver.executeScript('sessionStorage.getItem("userData");');
var firstCode = JSON.parse(j_userData).firstCode;
expect(firstCode).to.not.be.null;

答案 1 :(得分:0)

如果您尝试直接从量角器访问窗口对象/浏览器范围,则可能会因为“未定义窗口”而抛出错误,因为在尝试访问窗口对象/浏览器范围时可能未加载/定义。 / p>

解决方案

browser.executeScript('return window.sessionStorage.getItem("myKey");').then(function (myValue) { console.log('testcase myValue == ', myValue); });

您将在 myValue (console.log('testcase myValue ==',myValue))中获得整个对象。