</>

Technology

Cucumber

Difficulty

Intermediate

Interview Question

How do you handle a scenario where the application shows a cookie consent popup that blocks automation?

Answer

Handling Cookie Consent Popups in Cucumber

The Problem

Gherkin
Scenario: User searches for product
  Given the user navigates to the home page   ← cookie banner appears here
  When the user types "laptop" in search      ← FAILS: banner blocks the search box
  Then results should show

Solution 1: @Before Hook — Dismiss Banner Before Every Scenario

Java
package hooks;

import io.cucumber.java.Before;
import context.ScenarioContext;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.*;
import java.time.Duration;

public class CookieConsentHook {

    private final ScenarioContext ctx;

    public CookieConsentHook(ScenarioContext ctx) { this.ctx = ctx; }

    @Before(order = 50)  // runs after driver init, before test steps
    public void dismissCookieConsent() {
        try {
            WebDriverWait wait = new WebDriverWait(ctx.driver, Duration.ofSeconds(5));

            // Try common cookie consent button selectors
            String[] consentSelectors = {
                "[data-testid='cookie-accept']",
                "#cookie-consent-accept",
                ".cookie-banner button.accept",
                "button[id*='accept']",
                "button[class*='accept-cookie']",
                "//button[contains(text(), 'Accept All')]",
                "//button[contains(text(), 'Accept Cookies')]"
            };

            for (String selector : consentSelectors) {
                try {
                    WebElement btn = selector.startsWith("//")
                        ? wait.until(ExpectedConditions.elementToBeClickable(By.xpath(selector)))
                        : wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(selector)));
                    btn.click();
                    System.out.println("Cookie consent dismissed via: " + selector);
                    return;  // dismissed successfully
                } catch (TimeoutException | NoSuchElementException e) {
                    // try next selector
                }
            }

            System.out.println("No cookie consent banner found — proceeding");

        } catch (Exception e) {
            System.out.println("Cookie consent hook skipped: " + e.getMessage());
            // Never let this hook fail the actual test
        }
    }
}

Solution 2: JavaScript Click (When Normal Click Fails)

Java
@Before(order = 50)
public void dismissCookieBannerViaJS() {
    try {
        WebElement acceptBtn = ctx.driver.findElement(
            By.cssSelector("[data-testid='cookie-accept']"));

        if (acceptBtn.isDisplayed()) {
            ((JavascriptExecutor) ctx.driver).executeScript(
                "arguments[0].click();", acceptBtn);
        }
    } catch (NoSuchElementException e) {
        // No banner — normal scenario, do nothing
    }
}

Solution 3: ChromeOptions — Set Cookie at Browser Level

Java
// Inject cookie before page load — browser never shows consent banner
@Before(order = 40)  // before navigation
public void setConsentCookie() {
    ctx.driver.get(ConfigReader.getBaseUrl());  // navigate first to set domain

    ctx.driver.manage().addCookie(new Cookie(
        "cookieConsent",    // cookie name used by the app
        "accepted",         // accepted value
        ".example.com",     // domain
        "/",                // path
        null,               // no expiry → session cookie
        false,              // not secure (adjust per site)
        true                // httpOnly
    ));

    ctx.driver.navigate().refresh();  // reload with cookie set → no banner
}

Solution 4: Disable Consent Banner in Test Environment

Negotiate with developers to add a URL param or env flag:

Java
// Ask dev team to skip consent banner for test users
ctx.driver.get(ConfigReader.getBaseUrl() + "?disable_consent=true");

// Or configure via config property
ctx.driver.get(ConfigReader.getBaseUrl() + ConfigReader.get("consent.bypass.param"));

Solution 5: CookieUtils Reusable Helper

Java
public class CookieUtils {

    public static void dismissConsentBanner(WebDriver driver) {
        String[] selectors = {
            "[data-testid='cookie-accept']",
            "#onetrust-accept-btn-handler",   // OneTrust (common CMP)
            ".cc-btn.cc-allow",               // Cookie Consent.js
            "#CybotCookiebotDialogBodyButtonAccept"  // Cookiebot
        };

        for (String sel : selectors) {
            try {
                WebElement el = new WebDriverWait(driver, Duration.ofSeconds(3))
                    .until(ExpectedConditions.elementToBeClickable(By.cssSelector(sel)));
                el.click();
                return;
            } catch (Exception ignored) {}
        }
    }
}

Feature File — No Mention of Cookies

The feature file stays clean — cookie handling is purely in the hook:

Gherkin
-- No "And the user accepts cookies" step needed
Scenario: Search for product
  Given the user navigates to the home page
  When the user types "laptop" in the search box
  Then the search results should appear

The @Before hook handles consent automatically before the Given step runs.

Follow AutomateQA

Related Topics