From 48b851893757ab538fd786c8e2d49b6d311f3b46 Mon Sep 17 00:00:00 2001 From: Lee Rowlands Date: Tue, 19 Sep 2023 07:22:21 +1000 Subject: [PATCH] Issue #2031223 by Spokje, acbramley, Berdir, ravi.shankar, a_c_m: Add linkByHrefExistsExact and linkByHrefNotExistsExact for matching links by href exactly --- core/tests/Drupal/Tests/WebAssert.php | 44 +++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/core/tests/Drupal/Tests/WebAssert.php b/core/tests/Drupal/Tests/WebAssert.php index bb6f2bea2e3..d8f9006e3fd 100644 --- a/core/tests/Drupal/Tests/WebAssert.php +++ b/core/tests/Drupal/Tests/WebAssert.php @@ -387,6 +387,29 @@ class WebAssert extends MinkWebAssert { $this->assert(!empty($links[$index]), $message); } + /** + * Passes if a link with a given href is found. + * + * @param string $href + * The full value of the 'href' attribute of the anchor tag. + * @param int $index + * Link position counting from zero. + * @param string $message + * (optional) A message to display with the assertion. Do not translate + * messages: use \Drupal\Component\Render\FormattableMarkup to embed + * variables in the message text, not t(). If left blank, a default message + * will be displayed. + * + * @throws \Behat\Mink\Exception\ExpectationException + * Thrown when element doesn't exist, or the link label is a different one. + */ + public function linkByHrefExistsExact(string $href, int $index = 0, string $message = ''): void { + $xpath = $this->buildXPathQuery('//a[@href=:href]', [':href' => $href]); + $message = ($message ?: strtr('No link with href %href found.', ['%href' => $href])); + $links = $this->session->getPage()->findAll('xpath', $xpath); + $this->assert(!empty($links[$index]), $message); + } + /** * Passes if a link containing a given href (part) is not found. * @@ -408,6 +431,27 @@ class WebAssert extends MinkWebAssert { $this->assert(empty($links), $message); } + /** + * Passes if a link with a given href is not found. + * + * @param string $href + * The full value of the 'href' attribute of the anchor tag. + * @param string $message + * (optional) A message to display with the assertion. Do not translate + * messages: use \Drupal\Component\Render\FormattableMarkup to embed + * variables in the message text, not t(). If left blank, a default message + * will be displayed. + * + * @throws \Behat\Mink\Exception\ExpectationException + * Thrown when element doesn't exist, or the link label is a different one. + */ + public function linkByHrefNotExistsExact(string $href, string $message = ''): void { + $xpath = $this->buildXPathQuery('//a[@href=:href]', [':href' => $href]); + $message = ($message ?: strtr('Link with href %href found.', ['%href' => $href])); + $links = $this->session->getPage()->findAll('xpath', $xpath); + $this->assert(empty($links), $message); + } + /** * Builds an XPath query. *