Home

Testing storage with Selenium (Node)

How to test for key-value pairs in sessionStorage and localStorage using Selenium Node.

Originally posted on www.grouparoo.com.

We have a feature on this site that is using sessionStorage to send analytics data we want to capture. Being that it's an important feature, we should write test(s) to cover the use case(s), right?

Okay, fine. Let's do it!

This website is a Next.js application that uses Jest as our test runner and Selenium WebDriver for integration test help.

What I wanted to do with Jest and Selenium was to read from sessionStorage after visiting a series of pages. After a bit of perusing, I finally uncovered a (goofy) way to achieve what I wanted.

We can use the executeScript method to run a JavaScript expression and capture the result. Our test looks like this:

declare var browser: any;

async function getSessionItem(key) {
return await browser.executeScript(
`return window.sessionStorage.getItem("${key}");`
);
}

test("stores page history in the session data", async () => {
await browser.get(url + `/docs/config`);
expect(await getSessionItem("prevPath")).toBe("null");
expect(await getSessionItem("currentPath")).toBe("/docs/config");
await browser.get(url + `/meet`);
expect(await getSessionItem("prevPath")).toBe("/docs/config");
expect(await getSessionItem("currentPath")).toBe("/meet");
});

Here are a few of the key items to note:

  • You must return the JavaScript expression or you'll end up with undefined.
  • It's a much cleaner approach to run tests as async functions so you can use await to retrieve the result of the script, rather than ending up in a nightmarish Promise chain.
  • browser is often referred to as driver in other documentation and implementations. This comes from the library we're using to connect Jest and Selenium.

This now works like a charm! You could take a similar approach if you wanted to read from any other JavaScript object, including localStorage.

Let's Connect

Keep Reading

Get user's Previous Path with NextJS Router

How to find the previous page a user visited before landing on the current page.

Feb 17, 2021

Understanding Types with SQLite and Node.js

SQLite is simple but very cool and powerful. Yet, it's a little quirky when it comes to handling types. Let's explore that goofiness together, and see how we can protect against it when using Node.

Apr 22, 2021

Using Node.js to Check for Broken Links

A tutorial that walks through the process of writing a Node.js script to recursively test for broken links on a website.

Feb 03, 2023