Protractor element(..) returning undefined from a separate file

两盒软妹~` 提交于 2020-05-29 07:26:28

问题


I'm writing a Protractor test and in my test.step.js file I have

element(by.css('...')).getText().then(function (text) {
    expect(text).to.equal('expectedText');
});

This works as expected and passes.

Instead I created a test.page.js file and in there put this.field = element(by.css('...')); and then in my step file had

"use strict"

module.exports = function exampleTest() {
    var TestPage = require("...");
    var testPage = new TestPage;
    ...
    test.Then(..., function (next) {
       testPage.field.getText().then(function (text) {
          expect(text).to.equal('expectedText');
       });
    });
}

then field is undefined. I have also tried adding getText() in the page file, but again get undefined or get told that I can't call 'then' on undefined.

In my mind, this should do exactly the same thing as the first example, but I'm far from an expert with Angular or JavaScript.

test.page.js looks like:

"use strict";

module.exports = (function () {
    function TestPage() {
        this.field = element(by.css('...'));
    }

    return TestPage;
});

Hoping someone can shine some light on why this is happening and what I should do instead to be able to put the CSS selector inside a page file for re-use.

Thanks


回答1:


Your code new TestPage; returns the constructor TestPage, but it's never called.

You could return the class :

function TestPage() {
    this.field = element(by.css('...'));
}

module.exports = TestPage;
var TestPage = require("...");
var testPage = new TestPage;
testPage.field.getText().then(...

Or an instance of the class:

function TestPage() {
    this.field = element(by.css('...'));
}

module.exports = new TestPage();
var testPage = require("...");
testPage.field.getText().then(...



回答2:


The way you defined re-usable element locators looks different. I am following some thing like below

Step 1: Define a .js file which should contain the Locator objects and re-usable methods

var Login = {

    PageElements: {
        emailInput: element(by.css('#email')),
        passwordInput: element(by.css('#password')),
        loginForm: element(by.css('#form')),
    },
    doLogin: function doLogin() {
        this.PageElements.emailInput.sendKeys('blahblah@email.com');
        this.PageElements.passwordInput.sendKeys('blahblah');
        this.PageElements.loginForm.submit();
    },
};

module.exports = Login;

Step 2: Call these page objects in your test classes.

var LoginPage = require('../pageobjects/LoginPage.js');
it('Scenario1_Login',function(){
 LoginPage.PageElements.emailInput.sendKeys('blahblah');
});

More details here



来源:https://stackoverflow.com/questions/40001267/protractor-element-returning-undefined-from-a-separate-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!