The Question:
What is the canonical way to define nested Page Objects in Protractor?
Use Case:
We have a complicated page that consists of multiple parts: a filter panel, a grid, a summary part, a control panel on a side. Putting all the element and method definitions into a single file and a single page object does not work and scale - it is becoming a mess which is difficult to maintain.
The idea is define the Page Object as a package - directory with index.js
as an entry point. The parent page object would act as a container for child page objects which in this case have a "part of a screen" meaning.
The parent page object would be defined inside the index.js
and it would contain all the child page object definitions, for example:
var ChildPage1 = require("./page.child1.po"),
ChildPage2 = require("./page.child2.po"),
var ParentPage = function () {
// some elements and methods can be defined on this level as well
this.someElement = element(by.id("someid"));
// child page objects
this.childPage1 = new ChildPage1(this);
this.childPage2 = new ChildPage2(this);
}
module.exports = new ParentPage();
Note how
this
is passed into the child page object constructors. This might be needed if a child page object would need access to the parent page object's elements or methods.
The child Page Object would look like this:
var ChildPage1 = function (parent) {
// element and method definitions here
this.someOtherElement = element(by.id("someotherid"));
}
module.exports = ChildPage1;
Now, it would be quite convenient to use this kind of page object. You simply require the parent page object and use the dot notation to get access to the sub page objects:
var parentPage = requirePO("parent");
describe("Test Something", function () {
it("should test something", function () {
// accessing parent
parentPage.someElement.click();
// accessing nested page object
parentPage.childPage1.someOtherElement.sendKeys("test");
});
});
requirePO()
is a helper function to ease imports.
Sample nested page object directory structure from one of our test automation projects: