Careeroza
Skipping the Login Screen With Cookies
Inject the Session
If 200 tests start with logging in through the UI, the login form runs 200 times. Test login properly in a few dedicated tests; for the rest, get a session through the API and add the cookie to the browser.
public void loginViaApi(WebDriver driver, String email, String password) {
String sessionId = given().baseUri(ConfigReader.get("baseUrl"))
.contentType(ContentType.JSON)
.body(Map.of("email", email, "password", password))
.post("/api/auth/session")
.then().statusCode(200)
.extract().cookie("SESSION");
driver.get(ConfigReader.get("baseUrl") + "/robots.txt"); // must be on the domain before adding a cookie
driver.manage().addCookie(new Cookie.Builder("SESSION", sessionId)
.domain("qa.shopease.example.com").path("/").isHttpOnly(true).isSecure(true).build());
driver.get(ConfigReader.get("baseUrl") + "/account"); // already logged in
}Note: Selenium can only add a cookie for the domain of the page currently open, so open any light page on that domain first. Otherwise you get InvalidCookieDomainException.
Token in Local Storage
// Single-page apps often keep a JWT in localStorage instead of a cookie
driver.get(baseUrl);
((JavascriptExecutor) driver).executeScript(
"window.localStorage.setItem('authToken', arguments[0]);", token);
driver.navigate().refresh();Tip: Measure it: on ShopEase, API login saved about 4 seconds per test, or 13 minutes on a 200-test suite.