TestCafe Page Objects and Selectors: Maintainable Test Architecture
TestCafe's Selector API is the foundation of maintainable E2E tests. Combined with the page object pattern, it keeps your test code readable, centralized, and resilient to UI changes. This guide covers the full Selector API and shows how to structure page objects for real projects.
TestCafe Selector Basics
TestCafe's Selector is a lazy, chainable query that runs in the browser. Unlike Selenium's findElement, selectors are not evaluated until a test action uses them:
import { Selector } from 'testcafe';
// Basic CSS selector
const loginButton = Selector('#login-btn');
// By text content
const submitButton = Selector('button').withText('Submit');
// By attribute
const emailInput = Selector('input[type="email"]');
// Nested selection
const firstProductCard = Selector('.product-list').find('.product-card').nth(0);Selectors can also find elements by exact text, partial text, or custom predicates:
// Exact text match
const logoutLink = Selector('a').withExactText('Log out');
// Partial text match
const helpLink = Selector('a').withText('Help');
// Custom filter function (runs in browser context)
const firstVisibleButton = Selector('button').filter(node => {
return !node.disabled && node.offsetHeight > 0;
});Chained Selectors
Build complex queries by chaining selector methods:
// Find a table row that contains specific text, then get a cell within it
const priceCell = Selector('tr')
.withText('Premium Plan')
.find('td.price');
// Find the nth item in a filtered set
const thirdActiveUser = Selector('.user-row')
.filter('.active')
.nth(2);
// Traverse DOM relationships
const errorMessage = Selector('#email-input')
.parent('form')
.find('.field-error');Selector Properties and Assertions
Selectors expose element properties for assertions:
test('Product card displays correct information', async t => {
const productCard = Selector('.product-card').nth(0);
// Text content
await t.expect(productCard.find('.product-name').innerText).eql('Wireless Headphones');
// Attribute value
await t.expect(productCard.find('img').getAttribute('alt')).contains('Headphones');
// Existence
await t.expect(productCard.find('.sale-badge').exists).ok();
// Count
const starRatings = productCard.find('.star-icon');
await t.expect(starRatings.count).eql(5);
// CSS class
await t.expect(productCard.hasClass('featured')).ok();
// Visibility
await t.expect(Selector('.loading-spinner').visible).notOk();
});Custom Selectors with ClientFunction
For complex element lookups that CSS can't express, use ClientFunction:
import { ClientFunction } from 'testcafe';
// Get computed styles
const getComputedColor = ClientFunction(selector => {
const el = document.querySelector(selector);
return window.getComputedStyle(el).color;
});
// Find element by data attribute with specific value
const getProductByName = ClientFunction(name => {
const cards = document.querySelectorAll('.product-card');
for (const card of cards) {
if (card.dataset.productName === name) {
return card.dataset.productId;
}
}
return null;
});
test('Featured product has correct highlight color', async t => {
const color = await getComputedColor('.featured-product');
await t.expect(color).eql('rgb(255, 200, 0)');
});The Page Object Pattern
Page objects encapsulate element selectors and actions for a specific page. When the UI changes, you update one file instead of hunting through tests.
// pages/LoginPage.js
import { Selector, t } from 'testcafe';
export class LoginPage {
constructor() {
this.emailInput = Selector('#email');
this.passwordInput = Selector('#password');
this.loginButton = Selector('button[type="submit"]');
this.errorMessage = Selector('.auth-error');
this.forgotPasswordLink = Selector('a[href="/forgot-password"]');
}
async login(email, password) {
await t
.typeText(this.emailInput, email, { replace: true })
.typeText(this.passwordInput, password, { replace: true })
.click(this.loginButton);
}
async getErrorText() {
return this.errorMessage.innerText;
}
async clickForgotPassword() {
await t.click(this.forgotPasswordLink);
}
async isErrorVisible() {
return this.errorMessage.visible;
}
}
export const loginPage = new LoginPage();// pages/DashboardPage.js
import { Selector, t } from 'testcafe';
export class DashboardPage {
constructor() {
this.welcomeMessage = Selector('.welcome-banner');
this.userMenu = Selector('.user-menu-trigger');
this.logoutButton = Selector('.logout-option');
this.notificationBell = Selector('.notification-bell');
this.notificationCount = Selector('.notification-count');
}
async logout() {
await t
.click(this.userMenu)
.click(this.logoutButton);
}
async getWelcomeText() {
return this.welcomeMessage.innerText;
}
async getNotificationCount() {
return parseInt(await this.notificationCount.innerText, 10);
}
async isOnDashboard() {
return this.welcomeMessage.visible;
}
}
export const dashboardPage = new DashboardPage();Tests become clean and readable:
import { loginPage } from './pages/LoginPage';
import { dashboardPage } from './pages/DashboardPage';
fixture('User Authentication')
.page('https://example.com/login');
test('Successful login redirects to dashboard', async t => {
await loginPage.login('user@example.com', 'pass123');
await t.expect(dashboardPage.isOnDashboard()).ok();
const welcomeText = await dashboardPage.getWelcomeText();
await t.expect(welcomeText).contains('Welcome');
});
test('Wrong password shows error message', async t => {
await loginPage.login('user@example.com', 'wrongpass');
await t.expect(loginPage.isErrorVisible()).ok();
const error = await loginPage.getErrorText();
await t.expect(error).eql('Invalid email or password');
});Component Objects for Shared UI
For reusable UI components (modals, tables, dropdowns), create component objects:
// components/DataTable.js
import { Selector, t } from 'testcafe';
export class DataTable {
constructor(tableSelector) {
this.table = Selector(tableSelector);
this.rows = this.table.find('tbody tr');
this.headers = this.table.find('thead th');
this.sortableHeaders = this.table.find('thead th[data-sortable="true"]');
}
row(index) {
return this.rows.nth(index);
}
async rowCount() {
return this.rows.count;
}
async getCell(rowIndex, columnName) {
const headers = await this.headers;
let columnIndex = -1;
const headerCount = await headers.count;
for (let i = 0; i < headerCount; i++) {
const text = await headers.nth(i).innerText;
if (text.trim() === columnName) {
columnIndex = i;
break;
}
}
if (columnIndex === -1) throw new Error(`Column "${columnName}" not found`);
return this.rows.nth(rowIndex).find('td').nth(columnIndex);
}
async sortBy(columnName) {
const header = this.table
.find('thead th')
.withText(columnName);
await t.click(header);
}
}Use the component in page objects:
// pages/OrdersPage.js
import { DataTable } from '../components/DataTable';
export class OrdersPage {
constructor() {
this.ordersTable = new DataTable('#orders-table');
this.searchInput = Selector('#order-search');
}
async getOrderStatus(rowIndex) {
const cell = await this.ordersTable.getCell(rowIndex, 'Status');
return cell.innerText;
}
}Selector Best Practices
Prefer data-testid attributes. CSS classes and element structure change with styling updates. Test IDs stay stable:
<button data-testid="submit-order" class="btn btn-primary">Place Order</button>const submitButton = Selector('[data-testid="submit-order"]');Avoid XPath. XPath selectors are brittle and hard to read. TestCafe's CSS selector chaining can handle most use cases.
Keep selectors in page objects. Never define selectors inline in tests — put them in page objects so changes only require one update.
Test for visibility, not just existence. selector.exists can be true for hidden elements. Use selector.visible when testing what the user can see.
Use withText for user-facing content. Buttons and links are often best selected by their text content — it's what users see and what accessibility tools use.
Production Testing with HelpMeTest
TestCafe page objects give you a maintainable E2E test architecture for CI pipelines. For continuous production monitoring, HelpMeTest monitors your critical user flows around the clock — no TestCafe setup, no Node.js, no page object maintenance required. Tests run on a schedule; failures alert your team immediately.
Summary
TestCafe's Selector API is expressive and powerful — CSS selectors, text filtering, DOM traversal, and custom ClientFunction predicates handle any element lookup. Combined with the page object pattern, selectors become maintainable infrastructure rather than copy-paste noise. Structure your tests with LoginPage, DashboardPage, and shared component classes; centralize all selector definitions; and watch your test suite stay healthy as the UI evolves.