Xerces
Xerces

Reputation: 3

Cannot access 'element' before initialization in Protractor

I'm trying to write end-to-end test for Angular application using Protractor. I'm attempting to create a function which waits for an element to be present on page before accessing it, but I'm getting an error:

ReferenceError: Cannot access 'element' before initialization

although I did require element from Protractor.

The function is in file global.js:

const { browser, element } = require('protractor');

const global = function () {
  this.getElementAsync = (element, waitTime) =>
    browser.wait(() => element.isPresent(), waitTime)
    .then(() => browser.wait(() => element.isDisplayed(), waitTime));
  }
    
module.exports = new global();

And I'm using it in another file:

const global = require('./global');
const { element } = require('protractor');
    
var someFile = function () {
  this.doWhatever = async function(sec) {
    const element = await global.getElementAsync(element(by.css('.some.css')), 5000); //error is thrown here
    return element.click();
  };
}
    
module.exports = new someFile();

I'm open for all suggestions/advices.

Upvotes: 0

Views: 420

Answers (1)

Rudreshuar
Rudreshuar

Reputation: 125

You have a variable name collision on this line:

const element = await global.getElementAsync(element(by.css('.some.css')), 5000); //error is thrown here

element(by.css('.some.css') is trying to reference const element instead of the element import from protractor, thus the ReferenceError message.

Try changing your variable name to something else and it should work.

E.x:

const someElement= await global.getElementAsync(element(by.css('.some.css')), 5000);

Upvotes: 1

Related Questions