Test sessionStorage with Selenium Webdriver

learnAndImprove picture learnAndImprove · Dec 19, 2014 · Viewed 9.6k times · Source

I'm writing Java based selenium-webdriver tests. The app that I'm testing sets certain values in storageSession e.g. sessionStorage.setItem("demo", "test"), how can I check and assert the value of the stored variable demo inside my test

Answer

learnAndImprove picture learnAndImprove · Dec 19, 2014

Found a great utility class https://gist.github.com/roydekleijn/5073579

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;

public class LocalStorage {
  private JavascriptExecutor js;

  public LocalStorage(WebDriver webDriver) {
    this.js = (JavascriptExecutor) webDriver;
  }

  public void removeItemFromLocalStorage(String item) {
    js.executeScript(String.format(
        "window.localStorage.removeItem('%s');", item));
  }

  public boolean isItemPresentInLocalStorage(String item) {
    return !(js.executeScript(String.format(
        "return window.localStorage.getItem('%s');", item)) == null);
  }

  public String getItemFromLocalStorage(String key) {
    return (String) js.executeScript(String.format(
        "return window.localStorage.getItem('%s');", key));
  }

  public String getKeyFromLocalStorage(int key) {
    return (String) js.executeScript(String.format(
        "return window.localStorage.key('%s');", key));
  }

  public Long getLocalStorageLength() {
    return (Long) js.executeScript("return window.localStorage.length;");
  }

  public void setItemInLocalStorage(String item, String value) {
    js.executeScript(String.format(
        "window.localStorage.setItem('%s','%s');", item, value));
  }

  public void clearLocalStorage() {
    js.executeScript(String.format("window.localStorage.clear();"));
  }
}

thanks Roy