Darren Harley
Darren Harley

Reputation: 97

Click function not working within command script

In my nightwatchjs command script, I have the following code;

exports.command = function(searchMakeQueryPage) {
  var solrMakes = searchMakeQueryPage.Make.filter(val => typeof val === 'string');
  console.log('number of sorl makes = ', solrMakes.length);
  this.elements('css selector', '#bfsDesktopFilters #ddl-make option', function (dropDownMakes) {
    var numMakes = dropDownMakes.value.length;
    console.log('number of element makes = ', numMakes);
    this.assert.equal(solrMakes.length,numMakes-1);
});

  var makeResults = [];
  this.elements('css selector', '#bfsDesktopFilters .search-filters__item #ddl-make > option', function (numberOfMakes) {
    numberOfMakes.value.forEach(element => {
        this.elementIdValue(element.ELEMENT, function (text) {
            makeResults.push(text.value);
        });
    });

  this.perform(function(){
    var randomMake = makeResults[Math.floor(Math.random()*makeResults.length)];
    var randomMakeHref = randomMake.replace(/\s/g , '-');
    console.log('random make = ', randomMake);
    console.log('random make href = ', randomMakeHref);
    this.click(`#bfsDesktopFilters #ddl-make option[value="${randomMake}"]`);
  });
  });
};

which works, apart from the this.click(`#bfsDesktopFilters #ddl-make option[value="${randomMake}"]`); command.

When I run the test, I get the following error;

Error while running perform command: this.click is not a function

Is it the positioning of the brackets that's the issue here, or the positioning of the this.click(`#bfsDesktopFilters #ddl-make option[value="${randomMake}"]`) command that's the issue?

I've used the this.click command before in nightwatchjs command scripts, so I know it should be possible.

Any help would be greatly appreciated. Thanks.

Upvotes: 0

Views: 158

Answers (1)

Yaroslav Gaponov
Yaroslav Gaponov

Reputation: 2099

You need run click in right scope.

Method #1

exports.command = function(searchMakeQueryPage) {

  this.click = this.click.bind(this);

  this.perform(function(){
    this.click(`#bfsDesktopFilters #ddl-make option[value="${randomMake}"]`);
  });
};

Method #2

exports.command = function(searchMakeQueryPage) {

  var self = this;

  this.perform(function(){
    self.click(`#bfsDesktopFilters #ddl-make option[value="${randomMake}"]`);
  });
};

Method #3

exports.command = function(searchMakeQueryPage) {

  this.perform(() => {
    this.click(`#bfsDesktopFilters #ddl-make option[value="${randomMake}"]`);
  });
};

Upvotes: 1

Related Questions