Behat Scroll and Click on element

Profile picture for user devraj

Well, there could be multiple ways to scroll and click on element. Here, we will be using one of the way using executeScript method, which is used to execute JavaScript in browser.

For demo we will be using our website autopract.com.

Here is my feature file:

#language: en
@login
Feature:Verify scroll functionality

  Background:
    Given I am on homepage
    And I click on x button
  
  @scroll
  Scenario:
    When I fill in email with "goswami.tarun77@gmail.com"
    And I click on subscribe button

We will be clicking on the subscribe button after filling in my email which is present at the bottom of the page.

autopract subscribe button

You can find the step definition of subscribe button below:

 /**
   * @Given /^I click on subscribe button$/
   */
public function iClickOnSubmitButton()
{
    $page = $this->getSession()->getPage();
    $this->scrollAndClick("button.btn-solid");
}

Here we are calling scrollAndClick() method which is defined below:

    public function scrollAndClick($cssSelector)
    {
        $function = <<<JS
        (
            function()
            {
                document.querySelector("$cssSelector").scrollIntoView();
            }, function()
            {
                document.querySelector("$cssSelector").click();
            })() 
JS;
        try
        {
            $this->getSession()->executeScript($function);
        }
        catch (Exception $e)
        {
            throw new \Exception("Scroll Into View Failed. Check Your Script");
        }
    }

In $cssSelector you will get subscribe button css value which is button.btn-solid and after that we are performing scroll and click operation using document.querySelector. Here document object represent our webpage and querySelector is method which will get first element matching css value button.btn-solid

Tags