Accessing localStorage in Protractor test for AngularJS application
Asked Answered
V

1

18

I am writing some tests to verify that input data is being stored in local storage correctly, how can I access localStorage from within the protractor test?

...
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

How do you use executeScript? And could I get data from an executeScript?

Vindictive answered 22/2, 2014 at 21:9 Comment(1)
Zack, is there anything I can add or improve in the answer so we can resolve the topic and have the answer marked as accepted? Thanks!Urissa
U
39

To get an item from local storage use window.localStorage.getItem() through executeScript():

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

To clear local storage call clear():

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

We can also have this helper object/wrapper around the local storage for convenience:

"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();
Urissa answered 19/2, 2015 at 20:33 Comment(1)
For some reason both methods of getItem retrieves an undefined object no matter what and after I clearly inserted values into the localstorage. Can this be already deprecated (protractor 3.3, jasmine 2.4, angular 1.5.6)?He

© 2022 - 2024 — McMap. All rights reserved.