Rudolf Coutinho
Rudolf Coutinho

Reputation: 225

Error while trying to call variable from another file in js

I am using a page object model. So each page.js file contains a variable url and 'AddButtonId'. I call the function to launch the page by passing the pageName and elementID.

page.js

module.exports = {
    e: {
        url: 'http://localhost:4200/',
        AddButtonId: 'addButton',

},
};

function definition:

urlCall: function (pageName) {
          return  browser.get(pageName+".e.url");
        },

clickButton: function(pageName,elementID){
             var x = pageName+".e."+elementID;
             element(by.id(x)).click();
            },

here I pass pageName and ID while calling the function.

    urlcall(page);

    clickButton(page, AddButtonId);

But instead of getting the variable value (http://localhost:4200/) from the page object file, the browser.get() tries to load "pageName.e.url". Instead of passing "addButton" in "clickButton" function, it passes "page.e.AddButtonId" and fails with the error " NoSuchElementError: No element found using locator: By(css selector, *[id="page.e.AddButtonId"])"

Upvotes: 0

Views: 79

Answers (2)

yong
yong

Reputation: 13722

I think you need to import the page object by using the passed-in pageName to get the import file path.

// pageA.js

module.exports = {
    e: {
        url: 'http://localhost:4200/',
    },
    ...
};

// function: urlCall

urlCall: function (pageName) {
  // you need to import the page object.
  var page = require(pageName+'.js');
  var x = page.e.url;
  browser.get(x);
},

// function clickButton

clickButton: function(pageName,elementID){
    var page = require(pageName+'.js');
    var x = page.e[elementID];
    element(by.id(x)).click();
},

// test.js

urlCall('pageA')

Upvotes: 1

mk010101
mk010101

Reputation: 50

Javascript resolves your expression to a string. Instead, you need to use square brackets like pageName["e"]["url"] or proper property access: pageName.e.url

Upvotes: 0

Related Questions