Skip to main content

Testing sort order with BrowserTestBase

Just a quick post to share a simple way to assert some markup is ordered correctly using BrowserTestBase

by lee.rowlands /

Background

On a recent client project we received a bug report that the output of some particular markup wasn't sorted correctly.

Because we like to use test-driven-development, we obviously started with a test so we could be sure that the bug was fixed but also never appeared again.

Testing element order with BrowserTestBase

So as you'd be aware, BrowserTestBase in Drupal 8 is powered by Mink, which is pretty powerful.

In our test we created to pieces of fake content, title 'AAA Test' and 'BBB Test'.

If sorting was working, we'd expect to see 'AAA Test' before 'BBB Test'.

Both were output as links.

With BrowserTestBase and Mink, it was pretty simple.

// Grab all links with class .listing__title.
$links = $this->getSession()->getPage()->findAll('css', 'a.listing__title');
// Transform into an array keyed by link anchor.
$link_titles = array_flip(array_map(function ($link) {
  return $link->getText();
}, $links));
$this->assertTrue($link_titles['AAA Test'] < $link_titles['BBB Test']);

Not bad eh?

Do you have any handy Mink snippets? Share them in the comments.