Component Objects
Model headers, modals, tables and widgets as reusable component objects: scope searches to a root element, favour composition, and add loadable checks.
The Page Object Model works well until your app has fifty pages that all share the same header, the same data table, the same date picker and the same confirmation modal. Then the page objects start to rot in one of two ways: either every page object duplicates the locators and methods for the header, or a BasePage superclass grows into a 2,000-line god object that knows about every widget in the app.
Component objects (also called page components or page fragments) fix this by modelling the pieces of the UI, not just whole pages. A page object becomes a composition of components, and each component is a small class that owns one region of the DOM.
What Is a Component Object?
A component object is a class that:
- Wraps a root element: the DOM node that contains the component (the
header, thetable, the modal’s[role='dialog']). - Finds all of its children relative to that root, never through the global driver.
- Exposes behaviour in domain language (
header.search("widgets"),table.rowWhere("Order", "INV-1042")), not raw elements.
Because it is scoped to a root, the same class can model every instance of that component on any page, including several instances on the same page.
CheckoutPage├── Header (root: header[data-testid='app-header'])│ └── UserMenu (root: [data-testid='user-menu'])├── AddressForm x2 (roots: [data-testid='shipping-address'], [data-testid='billing-address'])├── OrderSummary (root: aside[data-testid='order-summary'])└── ConfirmDialog (root: [role='dialog'], appears on demand)Scoping Searches to a Root Element
Scoping is the heart of the pattern. root.findElement(...) searches only inside the root, which means a component’s locators can be short and generic (input[name='postcode']) without colliding with similar elements elsewhere on the page.
public abstract class Component { protected final WebDriver driver; protected final WebElement root;
protected Component(WebDriver driver, WebElement root) { this.driver = driver; this.root = root; }
protected WebElement find(By locator) { return root.findElement(locator); }
protected List<WebElement> findAll(By locator) { return root.findElements(locator); }
public boolean isDisplayed() { return root.isDisplayed(); }}
public class AddressForm extends Component { public AddressForm(WebDriver driver, WebElement root) { super(driver, root); }
public AddressForm fill(Address a) { type(By.name("line1"), a.line1()); type(By.name("city"), a.city()); type(By.name("postcode"), a.postcode()); return this; }
private void type(By locator, String value) { WebElement field = find(locator); field.clear(); field.sendKeys(value); }}class Component: def __init__(self, driver, root): self.driver = driver self.root = root
def find(self, by, value): return self.root.find_element(by, value)
def find_all(self, by, value): return self.root.find_elements(by, value)
@property def is_displayed(self): return self.root.is_displayed()
class AddressForm(Component): def fill(self, address): self._type(By.NAME, "line1", address.line1) self._type(By.NAME, "city", address.city) self._type(By.NAME, "postcode", address.postcode) return self
def _type(self, by, value, text): field = self.find(by, value) field.clear() field.send_keys(text)class Component {constructor(driver, root) { this.driver = driver; this.root = root;}
find(locator) { return this.root.findElement(locator);}
findAll(locator) { return this.root.findElements(locator);}
isDisplayed() { return this.root.isDisplayed();}}
class AddressForm extends Component {async fill(address) { await this.type(By.name('line1'), address.line1); await this.type(By.name('city'), address.city); await this.type(By.name('postcode'), address.postcode); return this;}
async type(locator, value) { const field = await this.find(locator); await field.clear(); await field.sendKeys(value);}}public abstract class Component{ protected readonly IWebDriver Driver; protected readonly IWebElement Root;
protected Component(IWebDriver driver, IWebElement root) { Driver = driver; Root = root; }
protected IWebElement Find(By locator) => Root.FindElement(locator); protected IReadOnlyCollection<IWebElement> FindAll(By locator) => Root.FindElements(locator); public bool IsDisplayed => Root.Displayed;}
public class AddressForm : Component{ public AddressForm(IWebDriver driver, IWebElement root) : base(driver, root) { }
public AddressForm Fill(Address a) { Type(By.Name("line1"), a.Line1); Type(By.Name("city"), a.City); Type(By.Name("postcode"), a.Postcode); return this; }
private void Type(By locator, string value) { var field = Find(locator); field.Clear(); field.SendKeys(value); }}The small Component base class is the one piece of inheritance in the pattern, and it only provides scoping helpers. Everything else is composition.
Warning: XPath inside a scoped search must start with
.to stay inside the root.root.findElement(By.xpath("//input"))searches the whole document, because//means “from the document root”. Use.//inputinstead. This is the most common bug in component objects and it fails silently by finding the wrong element.
Composing Pages from Components
A page object now creates components for its regions and exposes them:
public class CheckoutPage { private final WebDriver driver;
public CheckoutPage(WebDriver driver) { this.driver = driver; }
public Header header() { return new Header(driver, driver.findElement(By.cssSelector("[data-testid='app-header']"))); }
public AddressForm shippingAddress() { return new AddressForm(driver, driver.findElement(By.cssSelector("[data-testid='shipping-address']"))); }
public AddressForm billingAddress() { return new AddressForm(driver, driver.findElement(By.cssSelector("[data-testid='billing-address']"))); }
public ConfirmDialog placeOrder() { driver.findElement(By.cssSelector("[data-testid='place-order']")).click(); return ConfirmDialog.waitFor(driver); }}
// In a testCheckoutPage checkout = new CheckoutPage(driver);checkout.shippingAddress().fill(TestAddresses.LONDON);checkout.billingAddress().fill(TestAddresses.MANCHESTER);checkout.placeOrder().confirm();assertEquals("Ada Lovelace", checkout.header().userMenu().displayName());class CheckoutPage: def __init__(self, driver): self.driver = driver
@property def header(self): return Header(self.driver, self.driver.find_element(By.CSS_SELECTOR, "[data-testid='app-header']"))
@property def shipping_address(self): return AddressForm(self.driver, self.driver.find_element(By.CSS_SELECTOR, "[data-testid='shipping-address']"))
@property def billing_address(self): return AddressForm(self.driver, self.driver.find_element(By.CSS_SELECTOR, "[data-testid='billing-address']"))
def place_order(self): self.driver.find_element(By.CSS_SELECTOR, "[data-testid='place-order']").click() return ConfirmDialog.wait_for(self.driver)
# In a testcheckout = CheckoutPage(driver)checkout.shipping_address.fill(addresses.LONDON)checkout.billing_address.fill(addresses.MANCHESTER)checkout.place_order().confirm()assert checkout.header.user_menu.display_name == "Ada Lovelace"class CheckoutPage {constructor(driver) { this.driver = driver;}
async header() { return new Header(this.driver, await this.driver.findElement(By.css("[data-testid='app-header']")));}
async shippingAddress() { return new AddressForm(this.driver, await this.driver.findElement(By.css("[data-testid='shipping-address']")));}
async billingAddress() { return new AddressForm(this.driver, await this.driver.findElement(By.css("[data-testid='billing-address']")));}
async placeOrder() { await this.driver.findElement(By.css("[data-testid='place-order']")).click(); return ConfirmDialog.waitFor(this.driver);}}
// In a testconst checkout = new CheckoutPage(driver);await (await checkout.shippingAddress()).fill(addresses.LONDON);await (await checkout.billingAddress()).fill(addresses.MANCHESTER);await (await checkout.placeOrder()).confirm();public class CheckoutPage{ private readonly IWebDriver _driver;
public CheckoutPage(IWebDriver driver) => _driver = driver;
public Header Header => new(_driver, _driver.FindElement(By.CssSelector("[data-testid='app-header']")));
public AddressForm ShippingAddress => new(_driver, _driver.FindElement(By.CssSelector("[data-testid='shipping-address']")));
public AddressForm BillingAddress => new(_driver, _driver.FindElement(By.CssSelector("[data-testid='billing-address']")));
public ConfirmDialog PlaceOrder() { _driver.FindElement(By.CssSelector("[data-testid='place-order']")).Click(); return ConfirmDialog.WaitFor(_driver); }}
// In a testvar checkout = new CheckoutPage(driver);checkout.ShippingAddress.Fill(TestAddresses.London);checkout.BillingAddress.Fill(TestAddresses.Manchester);checkout.PlaceOrder().Confirm();Assert.That(checkout.Header.UserMenu.DisplayName, Is.EqualTo("Ada Lovelace"));Note that the accessors find the root each time they are called rather than caching the element in a field. In modern front ends, regions re-render often; a cached root goes stale and every call through it throws StaleElementReferenceException. Finding the root fresh is cheap and avoids an entire class of flakiness. Within a single short interaction (one fill call), holding the root is fine.
Root by locator vs root by element
An alternative design passes a By locator for the root and re-resolves it on every child lookup. That is even more resilient to re-renders, at the cost of an extra round trip per action. A reasonable rule: pass an element for components inside lists (table rows, cards), where you already have the element, and a locator for singleton regions (header, sidebar) that may re-render independently.
Composition Over Inheritance
The alternative to components is usually a BasePage that every page extends, with header, footer, navigation and modal methods built in. It looks tidy for a while. Then:
- Pages that do not have the standard header (login, error pages, embedded views) inherit methods that cannot work.
- The base class grows with every widget anyone needs on more than one page.
- Two “kinds” of page (admin layout vs customer layout) need different headers, and inheritance cannot express “has header A” vs “has header B” without more layers.
| Concern | Inheritance (BasePage) | Composition (components) |
|---|---|---|
| Reuse a header on 40 pages | Every page inherits it | Each page that has a header exposes one |
| Page without a header | Inherits broken methods | Simply does not expose it |
| Two different headers | Extra base classes | Two component classes |
| Same widget twice on one page | Awkward | Two instances with different roots |
| Testing the widget in isolation | Hard | Instantiate it against any root |
| Size of each class | Grows without bound | Stays small |
Keep inheritance for genuinely shared infrastructure (the Component base above, a wait helper). Model the UI with composition.
Components for Common Widgets
Modals and dialogs
Modals appear on demand, so their component needs a way to wait for them and to verify they have gone away.
public class ConfirmDialog extends Component { private static final By ROOT = By.cssSelector("[role='dialog'][aria-modal='true']");
private ConfirmDialog(WebDriver driver, WebElement root) { super(driver, root); }
public static ConfirmDialog waitFor(WebDriver driver) { WebElement root = new WebDriverWait(driver, Duration.ofSeconds(10)) .until(ExpectedConditions.visibilityOfElementLocated(ROOT)); return new ConfirmDialog(driver, root); }
public String message() { return find(By.cssSelector("[data-testid='dialog-message']")).getText(); }
public void confirm() { find(By.cssSelector("[data-testid='dialog-confirm']")).click(); new WebDriverWait(driver, Duration.ofSeconds(10)) .until(ExpectedConditions.invisibilityOf(root)); }
public void cancel() { find(By.cssSelector("[data-testid='dialog-cancel']")).click(); new WebDriverWait(driver, Duration.ofSeconds(10)) .until(ExpectedConditions.invisibilityOf(root)); }}class ConfirmDialog(Component): ROOT = (By.CSS_SELECTOR, "[role='dialog'][aria-modal='true']")
@classmethod def wait_for(cls, driver): root = WebDriverWait(driver, 10).until(EC.visibility_of_element_located(cls.ROOT)) return cls(driver, root)
@property def message(self): return self.find(By.CSS_SELECTOR, "[data-testid='dialog-message']").text
def confirm(self): self.find(By.CSS_SELECTOR, "[data-testid='dialog-confirm']").click() WebDriverWait(self.driver, 10).until(EC.invisibility_of_element(self.root))
def cancel(self): self.find(By.CSS_SELECTOR, "[data-testid='dialog-cancel']").click() WebDriverWait(self.driver, 10).until(EC.invisibility_of_element(self.root))class ConfirmDialog extends Component {static ROOT = By.css("[role='dialog'][aria-modal='true']");
static async waitFor(driver) { const root = await driver.wait(until.elementLocated(ConfirmDialog.ROOT), 10000); await driver.wait(until.elementIsVisible(root), 10000); return new ConfirmDialog(driver, root);}
async message() { return (await this.find(By.css("[data-testid='dialog-message']"))).getText();}
async confirm() { await (await this.find(By.css("[data-testid='dialog-confirm']"))).click(); await this.waitClosed();}
async cancel() { await (await this.find(By.css("[data-testid='dialog-cancel']"))).click(); await this.waitClosed();}
async waitClosed() { await this.driver.wait(async () => { try { return !(await this.root.isDisplayed()); } catch (e) { return true; // removed from the DOM counts as closed } }, 10000);}}public class ConfirmDialog : Component{ private static readonly By RootLocator = By.CssSelector("[role='dialog'][aria-modal='true']");
private ConfirmDialog(IWebDriver driver, IWebElement root) : base(driver, root) { }
public static ConfirmDialog WaitFor(IWebDriver driver) { var root = new WebDriverWait(driver, TimeSpan.FromSeconds(10)) .Until(d => d.FindElements(RootLocator).FirstOrDefault(e => e.Displayed)); return new ConfirmDialog(driver, root); }
public string Message => Find(By.CssSelector("[data-testid='dialog-message']")).Text;
public void Confirm() => ClickAndWaitClosed("[data-testid='dialog-confirm']"); public void Cancel() => ClickAndWaitClosed("[data-testid='dialog-cancel']");
private void ClickAndWaitClosed(string css) { Find(By.CssSelector(css)).Click(); new WebDriverWait(Driver, TimeSpan.FromSeconds(10)) .Until(SeleniumExtras.WaitHelpers.ExpectedConditions.InvisibilityOfElementLocated(RootLocator)); }}Returning the dialog from the action that opens it (placeOrder() returns ConfirmDialog) makes the flow discoverable: the test author’s IDE shows exactly what can happen next.
Table widgets
A data table component is one of the highest-value components in any app, because tables appear everywhere and the helpers are fiddly. The techniques from Working with Web Tables (header mapping, finding rows by cell value, pagination) belong in one DataTable class, and each row can itself be a component:
public class DataTable extends Component { public DataTable(WebDriver driver, WebElement root) { super(driver, root); }
private Map<String, Integer> columns() { List<WebElement> headers = findAll(By.cssSelector("thead th")); Map<String, Integer> map = new HashMap<>(); for (int i = 0; i < headers.size(); i++) map.put(headers.get(i).getText().trim(), i); return map; }
public List<TableRow> rows() { Map<String, Integer> cols = columns(); return findAll(By.cssSelector("tbody tr")).stream() .map(tr -> new TableRow(driver, tr, cols)) .toList(); }
public TableRow rowWhere(String column, String value) { return rows().stream() .filter(r -> r.cell(column).equals(value)) .findFirst() .orElseThrow(() -> new NoSuchElementException("No row with " + column + "=" + value)); }}
public class TableRow extends Component { private final Map<String, Integer> columns;
TableRow(WebDriver driver, WebElement root, Map<String, Integer> columns) { super(driver, root); this.columns = columns; }
public String cell(String column) { return findAll(By.tagName("td")).get(columns.get(column)).getText().trim(); }
public void open() { find(By.cssSelector("[data-testid='row-view']")).click(); }}
// UsageordersPage.table().rowWhere("Order", "INV-1042").open();class DataTable(Component): def _columns(self): headers = self.find_all(By.CSS_SELECTOR, "thead th") return {h.text.strip(): i for i, h in enumerate(headers)}
def rows(self): cols = self._columns() return [TableRow(self.driver, tr, cols) for tr in self.find_all(By.CSS_SELECTOR, "tbody tr")]
def row_where(self, column, value): for row in self.rows(): if row.cell(column) == value: return row raise NoSuchElementException(f"No row with {column}={value}")
class TableRow(Component): def __init__(self, driver, root, columns): super().__init__(driver, root) self.columns = columns
def cell(self, column): return self.find_all(By.TAG_NAME, "td")[self.columns[column]].text.strip()
def open(self): self.find(By.CSS_SELECTOR, "[data-testid='row-view']").click()
# Usageorders_page.table.row_where("Order", "INV-1042").open()class DataTable extends Component {async columns() { const headers = await this.findAll(By.css('thead th')); const map = new Map(); for (let i = 0; i < headers.length; i++) map.set((await headers[i].getText()).trim(), i); return map;}
async rows() { const cols = await this.columns(); const trs = await this.findAll(By.css('tbody tr')); return trs.map((tr) => new TableRow(this.driver, tr, cols));}
async rowWhere(column, value) { for (const row of await this.rows()) { if ((await row.cell(column)) === value) return row; } throw new Error('No row with ' + column + '=' + value);}}
class TableRow extends Component {constructor(driver, root, columns) { super(driver, root); this.columns = columns;}
async cell(column) { const cells = await this.findAll(By.css('td')); return (await cells[this.columns.get(column)].getText()).trim();}
async open() { await (await this.find(By.css("[data-testid='row-view']"))).click();}}
// Usageawait (await (await ordersPage.table()).rowWhere('Order', 'INV-1042')).open();public class DataTable : Component{ public DataTable(IWebDriver driver, IWebElement root) : base(driver, root) { }
private Dictionary<string, int> Columns() => FindAll(By.CssSelector("thead th")) .Select((h, i) => (Name: h.Text.Trim(), Index: i)) .ToDictionary(x => x.Name, x => x.Index);
public IEnumerable<TableRow> Rows() { var cols = Columns(); return FindAll(By.CssSelector("tbody tr")).Select(tr => new TableRow(Driver, tr, cols)); }
public TableRow RowWhere(string column, string value) => Rows().FirstOrDefault(r => r.Cell(column) == value) ?? throw new NoSuchElementException($"No row with {column}={value}");}
public class TableRow : Component{ private readonly Dictionary<string, int> _columns;
public TableRow(IWebDriver driver, IWebElement root, Dictionary<string, int> columns) : base(driver, root) => _columns = columns;
public string Cell(string column) => FindAll(By.TagName("td")).ElementAt(_columns[column]).Text.Trim();
public void Open() => Find(By.CssSelector("[data-testid='row-view']")).Click();}
// UsageordersPage.Table.RowWhere("Order", "INV-1042").Open();The JavaScript usage line shows a practical downside of async component accessors: nested awaits. Many JS teams make table() synchronous by passing a root locator instead of an element, then resolving it lazily inside each method. That keeps call sites flat.
Header, navigation and other singletons
The header is usually a thin component with a few actions (search, openUserMenu, logout) and nested components (UserMenu, NotificationsPanel). Nesting works the same way: a component creates sub-components from its own root.
Loadable Components
A loadable component knows how to check that it is ready (and optionally how to get there). Selenium’s Java support library ships a LoadableComponent<T> base class with load() and isLoaded() hooks; its get() method calls isLoaded(), loads if necessary, and checks again.
import org.openqa.selenium.support.ui.LoadableComponent;
public class OrdersPage extends LoadableComponent<OrdersPage> { private final WebDriver driver;
public OrdersPage(WebDriver driver) { this.driver = driver; }
@Override protected void load() { driver.get("https://app.example.com/orders"); }
@Override protected void isLoaded() throws Error { if (!driver.getCurrentUrl().contains("/orders")) { throw new Error("Not on the orders page: " + driver.getCurrentUrl()); } if (driver.findElements(By.cssSelector("tr[data-order-id]")).isEmpty()) { throw new Error("Orders table has no data yet"); } }
public DataTable table() { return new DataTable(driver, driver.findElement(By.id("orders"))); }}
// get() loads if needed, then verifies; wrap in a wait for async dataOrdersPage orders = new OrdersPage(driver).get();# No built-in base class in Python; a small mixin does the jobclass Loadable: def load(self): raise NotImplementedError
def is_loaded(self) -> bool: raise NotImplementedError
def get(self, timeout=10): if not self.is_loaded(): self.load() WebDriverWait(self.driver, timeout).until(lambda _: self.is_loaded()) return self
class OrdersPage(Loadable): def __init__(self, driver): self.driver = driver
def load(self): self.driver.get("https://app.example.com/orders")
def is_loaded(self): return ("/orders" in self.driver.current_url and bool(self.driver.find_elements(By.CSS_SELECTOR, "tr[data-order-id]")))
orders = OrdersPage(driver).get()// No built-in base class in JavaScript; a small base does the jobclass Loadable {async get(timeout = 10000) { if (!(await this.isLoaded())) await this.load(); await this.driver.wait(() => this.isLoaded(), timeout); return this;}}
class OrdersPage extends Loadable {constructor(driver) { super(); this.driver = driver;}
async load() { await this.driver.get('https://app.example.com/orders');}
async isLoaded() { const url = await this.driver.getCurrentUrl(); const rows = await this.driver.findElements(By.css('tr[data-order-id]')); return url.includes('/orders') && rows.length > 0;}}
const orders = await new OrdersPage(driver).get();// No built-in base class in .NET; a small base does the jobpublic abstract class Loadable<T> where T : Loadable<T>{ protected readonly IWebDriver Driver; protected Loadable(IWebDriver driver) => Driver = driver;
protected abstract void Load(); protected abstract bool IsLoaded();
public T Get(int timeoutSeconds = 10) { if (!IsLoaded()) Load(); new WebDriverWait(Driver, TimeSpan.FromSeconds(timeoutSeconds)).Until(_ => IsLoaded()); return (T)this; }}
public class OrdersPage : Loadable<OrdersPage>{ public OrdersPage(IWebDriver driver) : base(driver) { }
protected override void Load() => Driver.Navigate().GoToUrl("https://app.example.com/orders");
protected override bool IsLoaded() => Driver.Url.Contains("/orders") && Driver.FindElements(By.CssSelector("tr[data-order-id]")).Count > 0;}
var orders = new OrdersPage(driver).Get();Java’s LoadableComponent.get() checks once after loading; it does not wait. For SPAs with asynchronous data, either use SlowLoadableComponent (also in the Java support library, which retries isLoaded() until a timeout) or wrap the check in an explicit wait as the other languages do.
The same idea applies to components that are not pages. A modal’s waitFor factory and a table’s “has data rows” check are loadable semantics: the component refuses to hand itself to the test until it is usable. That single rule removes a large share of timing failures from component-based suites.
Design Guidelines
- One component, one region. If you cannot name the root element, the component is probably two components.
- Expose behaviour, not elements.
table.rowWhere(...), nottable.getRowsElements(). Returning rawWebElements lets locator knowledge leak into tests. - No assertions inside components. Components return state (
message(),cell(column)); tests assert. The exception is readiness checks, which are about synchronisation, not test outcomes. - Find roots lazily. Do not cache root elements in long-lived fields.
- Use
.//for scoped XPath. Or prefer CSS, which is always relative when called on an element. - Keep components framework-agnostic. A component that only needs a driver and a root works with any test runner and is trivially reusable across suites.
- Mirror the front-end’s component library. If developers have a
<DataTable>and<Modal>, have aDataTableandModalcomponent object. When the front-end component changes, you know exactly which test class to update.
Components also fit well with the Screenplay pattern (as the “UI targets” layer) and with Page Factory-style annotations in Java, though plain constructors as shown here are easier to reason about.
Common Pitfalls
| Symptom | Cause | Fix |
|---|---|---|
| Component acts on the wrong instance | XPath starting with // inside a scoped search | Use .// or CSS |
| Stale element errors after any update | Root element cached in a field | Re-find the root per accessor call |
| Base page class with hundreds of methods | Inheritance used for UI reuse | Extract components and compose |
Tests reach into component.root | Component exposes elements | Add behaviour methods instead |
| Modal methods fail intermittently | No wait for the modal to open/close | waitFor factory and close waits |
| Same table helpers in five page objects | No shared component | One DataTable component |
Summary
- Model reusable UI regions as components wrapping a root element.
- Scope every search to the root; use
.//for XPath. - Build page objects by composition; reserve inheritance for small infrastructure helpers.
- Write components for the widgets your app repeats: header, modals, tables, forms.
- Give components readiness checks so tests only receive usable objects.
Finished this lesson?
Mark it complete to track your progress through the course. Saved in this browser only.