3

I seem to be stuck in the construction of page objects. I read a lot of docs about page objects and know that they contain two things:

  • elements that are present on a page
  • functions to interact with the page

When I check example files I see that the elements are defined in the beginning of each page object. The in the test, the pageobject is imported via require. But the problem I see there is that the objects aren't yet present when the require happens. Is there another way to solve this without having to do a require just when the page is loaded?

Thanks inadvance. Regards

Homewrecker
  • 1,076
  • 1
  • 15
  • 38

2 Answers2

7

There is a new Protractor style guide coming up (currently in the review), which should clear things up a lot, especially the Page Object creation and requiring part. Here is the current draft:

Regarding your question, first of all, the Page Objects need to be defined as functions, declaring the page object elements in the constructor:

var QuestionPage = function() {
  this.question = element(by.model('question.text'));
  this.answer = element(by.binding('answer'));
  this.button = element(by.className('question-button'));

  this.ask = function(question) {
    this.question.sendKeys(question);
    this.button.click();
  };
};

module.exports = QuestionPage;

Then, require your page object at the top of the test suite:

var QuestionPage = require('./question-page');

describe('My Test', function() {
    ...
});

Instantiate your page object inside the test suite:

describe('My Test', function() {
  var questionPage = new QuestionPage();

  // specs
});
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
2

@alecxe's answer is solid, though personally, I prefer instantiating off the module.export thusly:

...
module.exports = new QuestionPage();

Thereby, you need only require it in your tests, not instantiate it in your tests. Whenever possible, I feel the scaffolding should be in the page object.

Brine
  • 3,733
  • 1
  • 21
  • 38