Protractor: Ability to manipulate localStorage, sessionStorage

Created on 28 Oct 2013  路  12Comments  路  Source: angular/protractor

Since AngularJS is webframework designed for SPAs, when using REST APIs, we shouldn't use cookies to store state of app. Instead, app should manage session by some kind of accessToken.

And so I did, I have REST API that verifies every request with accessToken app sends from browser. This token is transported in HTTP headers. I save token in localStorage, which is available from IE8+ (perfectly fine for my app).

In test some scenarios (redirecting of unpriviledged user to login screen) I need to clear my accessToken from localStorage. How can I do that?

question

Most helpful comment

I ran across the same issue. It would be nice if protractor maybe cleared the web storage before each scenario? I added the following afterEach to a global.js spec file and included it in the list of spec files when running protractor tests. If I don't clear the storage, the next scenario gets unexpected sessionStorage and localStorage data. This is a good work around for anyone that has the same problem. Works like a charm!

afterEach(function () {
    browser.executeScript('window.sessionStorage.clear();');
    browser.executeScript('window.localStorage.clear();');
});

All 12 comments

Protractor (more accurately WebDriver) allows you to execute javascript in the browser using the "executeScript" and "executeAsyncScript" methods (remember that these are webdriverjs methods, not protractors). It would be just like you did it in the browser console. So you could then write some javascript code that clears your local storage and insert and execute it in the browser during your beforeEach or afterEach steps (or whenever else you want to).

I ran across the same issue. It would be nice if protractor maybe cleared the web storage before each scenario? I added the following afterEach to a global.js spec file and included it in the list of spec files when running protractor tests. If I don't clear the storage, the next scenario gets unexpected sessionStorage and localStorage data. This is a good work around for anyone that has the same problem. Works like a charm!

afterEach(function () {
    browser.executeScript('window.sessionStorage.clear();');
    browser.executeScript('window.localStorage.clear();');
});

but how did you get the acces token from localstorage in protractor ?

probably? window.localStorage['key'] = value

I've been trying to do that but no luck. Anyone been able to successfully set something in localstorage? if so what did you do?

As good as it's going to get....
var item = browser.executeScript(" return window.localStorage.getItem('tokenName'); ");

In my case was doing so with Cucumber/Capybara testing. A browser instance must be started before you can access local or session storage, you can do this simply by using a 'visit' if you are using say, Cucumber/Capybara.

@chrisjlee You need window.localStorage.getItem(key) or window.localStorage.setItem(key, value).

@vargavince91 i am trying to do browser.executeScript("sessionStorage.setItem('selectedItems',[]);") but that is setting my selectedItems to undefined instead of []. It is because we are passing the argument in string to executeScript method. Does anyone know how to pass an empty array as a value to a key in this method.

@Mahendra-Kelapure-Infocepts I have some ideas as to why you don't receive what you think you should.

The first thing is that the return value of setItem is going to be undefined. This doesn't mean that it didn't set the donuts key to undefined. You can see that in your console.

> sessionStorage.setItem('donuts', 'a string')
< undefined
> sessionStorage.getItem('donuts')
< "a string"

This doesn't mean that it didn't set the item. You can run sessionStorage.getItem('donuts'), and that will return 'a string'.

The other thing is that setItem will convert anything to a string.

> sessionStorage.setItem('a', null)
> sessionStorage.getItem('a')
## The value going to be a string that contains the null text, but it's not the null value
< "null"

> sessionStorage.setItem('a', [])
> sessionStorage.getItem('a')
## It's going to set the value to empty string. What??? :) [].toString()
< ""

> sessionStorage.setItem('a', { obj: 3 })
> sessionStorage.getItem('a')
## Value is going to be a string again, with a value that's definitely not useful
< "[object Object]"

There's no way to convert a string that contains "[object Object]" back to an object { obj: 3 }. You need to serialize the value first, as setItem is not "clever" enough to do so. The most common solution is to use the JSON.stringify and JSON.parse functions.

> const thing = { counter: 4 }
> sessionStorage.setItem('thing', JSON.stringify(thing))
> sessionStorage.getItem('thing')
## it's going to be a string again, but this looks almost like the thing, so we can convert it back to JavaScript objects
< "{"counter":4}"
## With JSON.parse, you'll receive an object
> const thingBack = JSON.parse(sessionStorage.getItem('thing'))
## The value can be used as expected, for example increment value
> thing.counter++
## Verify it's incremented
> thing.counter
< 5

You should try:

browser.executeScript("sessionStorage.setItem('selectedItems',JSON.stringify([]));")

Let me know if that works.

@vargavince91 it is working now. thanks for the help!

@vargavince91 thanks for the explanation on session storage

@Mahendra-Kelapure-Infocepts If some of these conversions surprised you, I suggest you read the You don't know JavaScript books https://github.com/getify/You-Dont-Know-JS If you don't have the time and you just want a laugh, watch the WAT talk https://www.destroyallsoftware.com/talks/wat

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nt3rp picture nt3rp  路  3Comments

amedvedjev picture amedvedjev  路  3Comments

vishalshivnath picture vishalshivnath  路  3Comments

koshkarov picture koshkarov  路  3Comments

rafalf picture rafalf  路  3Comments