Protractor Page objects - TypeError: Object #<O

2019-06-01 18:50发布

问题:

I'm trying to write a simple test using page objects pattern - based on the 'docs/page-objects'.

I created a file describing the page object and other using this page object to test a page.

//page object
var LoginPage = function() {

this.userInput = browser.driver.findElement(by.id('username'));
this.pwdInput  = browser.driver.findElement(by.id('password'));
this.btnEnter  = browser.driver.findElement(by.id('btnLogin'));

this.get = function(){
    browser.get('http://example.com');
};

this.setUser = function (user){
    this.userInput.sendKeys(user);  
};

this.setPasswd = function (password) {
    this.pwdInput.sendKeys(password);
};

this.clickBtnEnter = function (){
    btnEnter.click();
};};

The spec file:

var loginPage = require('./LoginPage.js');
describe('myApp', function() {
  it('should save contract config', function (){        
    loginPage.get();
    loginPage.setUser('userid');
    loginPage.setPasswd('passwd');
    loginPage.clickBtnEnter();
  });
});

The following error is shown when I run this test: TypeError: Object # has no method 'get' - at this line: loginPage.get();.

When I was searching for this problem I found various approaches about using page objects in Protractor, such as Astrolable. Now I am not sure about the correct usage of page objects.

Do you have any ideas about how I can fix this test?

Thank you guys.

回答1:

Try this:

Ensure you have the following in your LoginPage.js file

module.exports = LoginPage;

Add the missing new keyword

var LoginPage = require('./LoginPage.js');
var loginPage = new LoginPage();


回答2:

After trying the above syntax (no success) I rewrote the page object using the Astrolable. Now it works! My test looks like this:

//pageobject
'use strict';
var env = require('./environment.js')

var LoginPage = function () {
  browser.driver.get('http://example.com');
};

LoginPage.prototype = Object.create({}, {

userInput:         {    get: function()    { return browser.driver.findElement(by.id('username'));}},
pwdInput:          {    get: function() { return browser.driver.findElement(by.id('password'));}},
btnEnter:          {    get: function()    { return browser.driver.findElement(by.id('btnLogin'));}},

setUser:           {     value: function (loginName) {
    this.userInput.sendKeys(loginName);        
}},

setPasswd: { value: function (loginPass) {
    this.pwdInput.sendKeys(loginPass);
}},

clickBtnEnter:    {    get: function()    { return this.btnEnter.click();}}    
});

module.exports = LoginPage;

Spec file:

'use strict';
var loginPage = require('./LoginPage.js');

describe('myApp', function() {
    var poLogin = new loginPage();

    it('should save contract config', function (){        
        poLogin.setUser('userid');
        poLogin.setPasswd('passwd');
        poLogin.clickBtnEnter;
    });
});

Now it is working fine. Thanks for answering.