Reusing Page Objects in the Middle of a Test

Overview

Page Objects (POs) are powerful for creating reusable and maintainable tests. However, a PO that works perfectly at the start of a test may fail when it is reused later in the same test flow. This typically happens because the application is not in the state the PO expects. This guide explains how to diagnose and solve this common issue.

How It Works

The Problem

A test uses a Page Object, for example, a 'Login' PO, at the beginning of a test and it executes successfully. Later in the test, after performing other actions like navigating through the application and logging out, the same 'Login' PO is called again. This time, it fails because it cannot find the expected elements, such as the username field, password field, or sign-in button.

Root Cause: Incorrect Application State

Page Objects are designed to execute a specific sequence of actions, and they assume the application is in a particular starting state. For a login PO, the required state is having the login page loaded in the browser. If the test has already logged out, the application might be on a logout confirmation screen or the homepage, not the login page. The PO does not automatically navigate to the correct starting page; it simply tries to execute its steps on whatever page is currently active.

The Solution: Add a Navigate Step

To ensure a Page Object executes correctly when called in the middle of a test, you must first place the application into the required state. This is usually done by adding a Navigate action right before the PO is called.

  1. Identify the correct starting URL that the Page Object requires. For a login PO, this would be the URL of the sign-in page.
  2. In your test flow, add a Navigate action on the step immediately before the Page Object action.
  3. Configure the Navigate action to go to the required URL.

By adding this navigation step, you ensure that when the Page Object begins, the application is on the correct page. This allows the PO to find its target elements and run successfully, regardless of where it is called in the test flow.

Related Information