在AngularJS应用程序的Protractor测试中访问localStorage

时间:2014-02-22 21:09:04

标签: javascript angularjs testing protractor local-storage

我正在编写一些测试来验证输入数据是否正确存储在本地存储中,如何从量角器测试中访问localStorage?

...
describe('vgPersist', function() {
  it('Should save input data in local storage until form submitted', function() {
    // Prepare Object and Open browser
    var addOns = new AddOns();
    addOns.get();

    -> Clear localStorage
    -> Get from localStorage

你如何使用executeScript?我可以从executeScript获取数据吗?

1 个答案:

答案 0 :(得分:27)

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

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

清除本地存储空间,请致电clear()

browser.executeScript("window.localStorage.clear();");

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

"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();