简体   繁体   中英

Promise not getting resolved when using Page Object Model with Protractor

I'm trying to implement the Page Object Model in my project, and I'm having trouble getting it to work. I want to the title of the current page using browser.getTitle(), which works perfectly when used directly in login.spec.js , but doesn't work when moved to login.po.js . Here's what my setup currently looks like:

login.spec.js

var LoginPage = require('../../pages/user/login.po.js'),
    expect = require('chai').expect;

describe('Login', function() {
    var page;

    beforeEach(function () {
        page = new LoginPage();
    });

    it('should be able to get the page title', function() {
        expect(page.getLoginPageTitle).to.equal('Test');
    });
});

login.po.js

'use strict';

var LoginPage = function(){
    browser.get('http://localhost:3000/');
};

LoginPage.prototype = Object.create({}, {
    getLoginPageTitle: {get: function() {
        browser.getTitle().then(function(res){
            return res;
        });
    }}
});

module.exports = LoginPage;

And the error I get: AssertionError: expected undefined to equal 'Test'

Upon further investigating, it seems like the browser.getTitle() promise in my login.po.js isn't getting resolved.

Any ideas on what I'm doing wrong? The page loads correctly in Chrome and Chrome shows the correct page title.

you should add an extra return in your PageObject. You are returning the result of the resolved promise browser.getTitle() , but not the promise itself, see below.

 'use strict'; var LoginPage = function() { browser.get('http://localhost:3000/'); }; LoginPage.prototype = Object.create({}, { getLoginPageTitle: { get: function() { return browser.getTitle(); } } }); module.exports = LoginPage; 

Figured it eventually! (no pun intended)

I simply had to use chai-as-promised as well as use wswebcreation 's answer. Here's my setup now:

login.spec.js

var LoginPage = require('../../pages/user/login.po.js'),
    chai = require('chai'),
    expect = require('chai').expect,
    chaiAsPromised = require('chai-as-promised');

chai.use(chaiAsPromised)

describe('Login', function() {
    var page;

    beforeEach(function () {
        page = new LoginPage();
    });

    it('should be able to get the page title', function() {
        expect(page.getLoginPageTitle).to.eventually.equal('Test');
    });
});

login.po.js

'use strict';

var LoginPage = function(){
    browser.get('http://localhost:3000/');
};

LoginPage.prototype = Object.create({}, {
    getLoginPageTitle: {get: function() {
        return browser.getTitle();
    }}
});

module.exports = LoginPage;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM