Protractor right approach to page object model



  • On Investigating on protractor page object model, i came across the below two approaches:

    First:

    var AngularHomepage = function() {
       var nameInput = element(by.model('yourName'));
       var greeting = element(by.binding('yourName'));
    
       this.get = function() {
          browser.get('http://www.angularjs.org');
       };
    
       this.setName = function(name) {
          nameInput.sendKeys(name);
       };
    
       this.getGreetingText = function() {
          return greeting.getText();
       };
    };
    module.exports = new AngularHomepage();
    ```
    
    
    

    Second

    'use strict';  
    
    module.exports = {  
        toDo: {  
            addField: element(by.css('[placeholder="add new todo here"]')),  
            checkedBox: element(by.model('todo.done')),  
            addButton: element(by.css('[value="add"]'))  
        },  
    
        go: function() {  
            browser.get('https://angularjs.org/'); //overrides baseURL  
            browser.waitForAngular();  
        },  
    
        addItem: function(item) {  
            var todo = this.toDo;  
    
            todo.addField.isDisplayed();  
            todo.addField.sendKeys(item);  
            todo.addButton.click();  
        }  
    };
    ```
    
    
    

    The second approach looked more clean and looked promising, could someone suggest which one should i go for. If you have any additional styles , please do help me with it.



  • I never really used protractor, but I built some tests in JavaScript. I would prefer the second one, as it does not have this this this everywhere. I think it is more readable.

    You can also wrap it in a function again to make it a bit more descriptive, and so you can include a sort of private methods.

    I structured my JavaScript tests like this:

    const browser = constructBrowser();
    const MyPage = require('./pagename.pageobject.js')({ browser });
    
    it('test MyPage', () => {
      MyPage.open();
      MyPage.action();
    });
    ```
    
    
    

    pagename.pageobject.js:

    module.exports = function Page(options) {
      if (!options.browser) throw Error('options.browser is required');
      const { browser } = options;
    
      const nav = By.className('nav');
      const button = By.className('btn');
      const url = 'http://server/';
    
      return {
        open: () => {
          browser.get(url);
        },
        action: () => {
          browser.findElement(nav).click();
          privateFnc();
        },
      };
    
      function privateFnc() {
          browser.findElement(btn).click();
      };
    };
    ```
    
    
    

    Have a look at my project at Github: https://github.com/nreijmersdal/stoppable/tree/master/test/integration



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2