简体   繁体   English

使用 Selenium Webdriver 测试 sessionStorage

[英]Test sessionStorage with Selenium Webdriver

I'm writing Java based selenium-webdriver tests.我正在编写基于 Java 的 selenium-webdriver 测试。 The app that I'm testing sets certain values in storageSession eg sessionStorage.setItem("demo", "test") , how can I check and assert the value of the stored variable demo inside my test我正在测试的应用程序在 storageSession 中设置了某些值,例如sessionStorage.setItem("demo", "test") ,我如何在我的测试中检查和断言存储变量demo的值

Found a great utility class https://gist.github.com/roydekleijn/5073579 找到了一个很棒的实用程序类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 谢谢罗伊

Expanding on the answer from @learnAndImprove which shows how to retrieve the local storage info, here is the piece we can add to that class to get the session storage.扩展来自@learnAndImprove的答案,它显示了如何检索本地存储信息,这是我们可以添加到 class 以获得 session 存储的部分。

public String getItemFromSessionStorage(String key) {
    return (String) js.executeScript(String.format(
            "return sessionStorage.getItem('%s');", key));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM