Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Page Object Model with Selenium and JavaScript

· 4 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

The Page Object Model (POM) is a design pattern that helps you organize Selenium test code by separating page-specific elements and actions from your test logic. Instead of writing selectors and actions directly inside test cases, you create a class (or object) for each page or component. This makes tests easier to read, maintain, and update when the UI changes. This guide walks you through setting up POM in a JavaScript Selenium project, from installing dependencies to writing your first page object and test.

What You'll Need

  • Node.js and npm installed on your machine (version 14 or later recommended).
  • A code editor (VS Code, Atom, etc.).
  • Basic familiarity with JavaScript (ES6 classes, async/await).
  • A Selenium WebDriver compatible browser (Chrome, Firefox, etc.) and the corresponding driver (e.g., chromedriver) available on your PATH or configured.
  • A test runner or framework – we'll use Mocha and Chai in this guide, but you can adapt to Jest or others.

Step-by-Step

  1. Initialize your project
    Create a new folder and run npm init -y to generate a package.json file.
  2. Install dependencies
    Run npm install selenium-webdriver mocha chai to install Selenium WebDriver, Mocha, and Chai. Also install the driver for your browser, e.g., npm install chromedriver (or geckodriver for Firefox).
  3. Set up a base page class
    Create a file BasePage.js. This class will hold common methods like open(url), findElement(locator), and click(locator). It takes a driver instance in its constructor and exposes it to subclasses.
  4. Create a page object for a specific page
    For example, create LoginPage.js that extends BasePage. Define locators as static strings (e.g., this.usernameInput = By.id('username')). Add methods like enterUsername(text), enterPassword(text), and clickLogin() that use the base class methods.
  5. Write test cases using the page object
    In your test file (e.g., login.test.js), import the page object. In the beforeEach hook, create a new WebDriver instance and instantiate the page object. In the test, call the page object's methods to interact with the page, and use Chai assertions to verify expected results.
  6. Run the tests
    Add a script to package.json: "test": "mocha". Run npm test in the terminal. Ensure your WebDriver is properly configured to find the browser driver.
  7. Refactor and expand
    As you add more pages, create a page object for each. If multiple pages share components (like a header), create a Component class and reuse it. Keep locators and actions in one place per page.

Common Mistakes

  • Putting assertions inside page objects – Page objects should only interact with the page and return results; assertions belong in test files.
  • Not using async/await – Selenium WebDriver methods return promises; forgetting to await them causes flaky tests.
  • Hardcoding URLs inside page objects – Instead, pass the base URL in the constructor or use a config file.
  • Creating a new driver for each test without cleanup – Always quit the driver in afterEach to avoid memory leaks.
  • Making locators too brittle – Avoid using absolute XPath; prefer IDs, CSS classes, or data attributes.

Tips

  • Use By.css or By.xpath consistently. CSS selectors are usually faster and more readable.
  • Keep locators as private constants at the top of the page class to make updates easy.
  • Return this from methods that don't return a value to allow method chaining (e.g., loginPage.enterUsername('user').enterPassword('pass').clickLogin()).
  • Use a configuration file for environment-specific values like base URL and browser type.
  • Consider using a page object for each component (e.g., navigation bar) to avoid duplication.

Troubleshooting

Test fails with "NoSuchElementError" – Check that the locator is correct and the element is present in the DOM at the time of interaction. Use explicit waits (e.g., driver.wait(until.elementLocated(locator), 10000)) instead of implicit waits or hardcoded sleeps.

Driver not found error – Ensure the browser driver is installed and on your PATH. Alternatively, set the PATH variable to include the driver's directory, or use a driver manager like selenium-manager.

Tests run but are flaky – Add explicit waits for elements that appear after animations or AJAX calls. Avoid using thread.sleep(); use driver.wait() with expected conditions.

Page object methods not working – Check that you are using async methods and awaiting them. Also verify that the driver instance is passed correctly to the page object constructor.

Frequently Asked Questions

Do I need a page object for every page?

Not necessarily. Start with pages that have many interactions. For simple pages, you can test directly, but as the suite grows, you'll benefit from consistency.

Can I use Page Object Model with Cucumber or other BDD frameworks?

Yes, POM works well with any test framework. You can call page object methods from your step definitions.

How do I handle dynamic elements?

Use relative XPath or CSS selectors that target stable attributes. For elements that change, consider using data-testid attributes if available.

Should I use implicit or explicit waits?

Explicit waits are preferred because they are more reliable and faster. Implicit waits can cause unexpected delays.

Can I use POM with Selenium Grid?

Yes, you can pass a remote WebDriver URL to the driver constructor. The page objects remain the same.

How do I structure large projects with many pages?

Create a pages folder and group related pages in subfolders. Use a base page class to share common methods.