Drupal 8 Behat Testing for a URL

Viewed 204

I'm new to Behat testing for my Drupal 8 site and trying to write a scenario to test that a URL does not exist on a page, but I can't seem to get it to work. The body field has a <a href="www.google.com"> cool</a> element.

@api

Feature: URL Scenario: Find a URL Given I am on "/hello" Then I should not see the link "www.google.com"

public function iShouldNotSeeTheLink($href, $index = 0, $message = '') {
    $xpath = $this
      ->buildXPathQuery('//a[contains(@href, :href)]', [
      ':href' => $href,
    ]);
    $message = $message ? $message : strtr('Link containing href %href found.', [
      '%href' => $href,
    ]);
    $links = $this->session
      ->getPage()
      ->findAll('xpath', $xpath);
    $this
      ->assert(!empty($links[$index]), $message);
  }
1 Answers

I ended up getting this to work and thought I'd post in case someone else needed it, it's probably not the best but it works for what I require.

    public function iClickOnTheElementWithXPath($xpath)
{
    $session = $this->getSession(); // get the mink session
    $element = $session->getPage()->find(
        'xpath',
        $session->getSelectorsHandler()->selectorToXpath('xpath', $xpath)
    ); // runs the actual query and returns the element

    // errors must not pass silently
    if (null === $element) {
        throw new \InvalidArgumentException(sprintf('Could not evaluate XPath: "%s"', $xpath));
    }
    
    // ok, let's click on it
    $element->click();

}

  Scenario: yahoo link check
Given I am on "/hello"
Given I click on the element with xpath "//a[not(contains(@href,'yahoo.com'))]"
Related