A cookie is a piece of information which saves information on the hard disk of the user's computer.
Websites can use it to track users, save preferences for the user or save any other data.
Cookies can be set to expire at a certain time, or to be saved permanently (at least until the user decides to wipe all cookies).
Handling cookies during your automated testing is a common task, since most websites are using cookies to track and retain specific user information.
We will discuss several topics related to handling cookies while running automated tests.
You can also read the Selenium documentation regarding working with cookies.
Why do I need to handle cookies during automated testing?
Websites may use cookies for different purposes, including saving data during a visitor session.
A potential problem might happen while running automated tests. The website under test might be saving specific data in the same cookie for multiple tests.
For example, let's say you are testing a shopping cart by adding an item. If one test adds the item to the cart, data might be saved in a cookie.
The second test might have logic which assumes that the cart is empty.
The cookie from the first test is still stored however, resulting in a test failure for the second test.
It's important to make sure that your tests always start from a pristine state, without any previous test data.
At TestingBot, we make sure every test start from a pristine, single-use virtual machine.
Anatomy of a cookie
A cookie may contain the following data:
- Name: This flag contains the name of the cookie.
- Value: This flag contains the value of the cookie.
- Domain: This determines on which domain the cookie resides.
- Path: This flag contains the URL required in the requested URL.
- Expires / Max-Age: The expiration date or the maximum age of the cookie.
- HttpOnly: Should this cookie be used only over HTTP?
- Secure: This determines if the cookie can only be sent over HTTPS.
- SameSite: This flag contains the values (strict or lax) if the cookie is using the experimental SameSite attribute.
Strict Cookie
When the sameSite
attribute is set to Strict, cookies will not be sent to third-party websites.
Lax Cookie
When the sameSite
attribute is set to Lax, cookies will be sent with GET requests to third-party websites.
How to use cookies with Selenium?
Selenium WebDriver offers various methods to interact with cookies:
-
Get cookie:
Gets all cookies or a specific cookie, by name, for the current domain. You can use this to get the value, or check if the cookie exists.
-
Add cookie:
Adds a cookie for the current domain:
const {Builder} = require('selenium-webdriver'); (async function example() { let driver = new Builder() .forBrowser('chrome') .build(); await driver.get('https://testingbot.com'); // Add a cookie, named "newCookieKey" with value "newCookieValue" await driver.manage().addCookie({name:'newCookieKey', value: 'newCookieValue'}); await driver.quit() })();
using OpenQA.Selenium; using OpenQA.Selenium.Chrome; namespace AddCookie { class AddCookie { public static void Main(string[] args) { IWebDriver driver = new ChromeDriver(); try { // Navigate to Url driver.Navigate().GoToUrl("https://testingbot.com"); // Add a cookie, named "newCookieKey" with value "newCookieValue" driver.Manage().Cookies.AddCookie(new Cookie("newCookieKey", "newCookieValue")); } finally { driver.Quit(); } } } }
-
Delete cookie:
Deletes a specific cookie, or all cookies for the current domain.
Iterate over all cookies
Let's see another example where we iterate over all available cookies and print the contents of each cookie, for debugging purposes:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class CookiesExample {
public static void main(String args[]) {
System.setProperty("webdriver.chrome.driver", "ChromeDriver Path");
WebDriver driver = new ChromeDriver();
String url ="https://testingbot.com/";
driver.get(url);
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
Set<Cookie> cookiesList = driver.manage().getCookies();
for (Cookie getcookies :cookiesList) {
System.out.println(getcookies);
}
driver.close();
}
}
You can modify the loop to delete specific cookies, or write the contents to a file as a test artifact.
Replacing cookies
To replace a cookie during an automated test, we suggest deleting the specific cookie and setting a new cookie with the same name.
Expiring cookies
Cookies have a expiry
flag which browsers use to automatically expire specific cookies.
To set a cookie with an expiration date via Selenium, please use the expiry
argument in the Cookie constructor:
How to use the Selenium Cookie API with a Selenium Grid?
To use the Selenium Cookie API with a Selenium Grid, you can use RemoteWebdriver and call the Selenium Cookie methods on the RemoteWebDriver object.
Instead of running your Selenium tests on your local computer, you might want to run tests on a (Cloud) Selenium grid. This offers great advantages, such as:
- Increased scalability: run tests in parallel on a Cloud grid such as TestingBot.
- Increased reliability: tests can be retried automatically when a connection/OS issue is detected.
- Performance: you can run the browser tests on more powerful computers than your own computer.
Please see the example below on how to clear cookies during a TestingBot test:
import org.openqa.selenium.By;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.URL;
public class JavaSample {
public static final String URL = "https://key:secret@hub.testingbot.com/wd/hub";
public static void main(String[] args) throws Exception {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("browserName", "IE");
caps.setCapability("version", "11");
caps.setCapability("platform", "WIN10");
caps.setCapability("name", "My First Test");
WebDriver driver = new RemoteWebDriver(new URL(URL), caps);
driver.get("http://www.google.com/ncr");
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("TestingBot");
element.submit();
System.out.println(driver.getTitle());
driver.quit();
}
}
public void deleteSpecificCookie(RemoteWebDriver driver, String cookieName) {
driver.manage().deleteCookie(cookieName);
}
public void deleteAllCookies(RemoteWebDriver driver) {
System.out.println("Deleting all cookies");
driver.manage().deleteAllCookies();
}