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.

Posted by Lee Rowlands
Senior Drupal Developer

Dated

Add new comment

Restricted HTML

  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <h2> <h3> <h4> <h5> <h6>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
Not sure where to start? Try typing "hello" or "help" if you get stuck.