Assert DOM Elements in Laravel Tests

Packages

November 3rd, 2022

Assert DOM Elements in Laravel Tests

The Laravel DOM Assertions package by René Sinnbeck adds document object model (DOM) assertion helpers to Laravel's TestResponse class:

This package provides some extra assertion helpers to use in HTTP Tests. If you have ever needed more control over your view assertions than assertSee, assertSeeInOrder, assertSeeText, assertSeeTextInOrder, assertDontSee, and assertDontSeeText then this is the package for you.

The package's README has an example of asserting a navigation menu to ensure the correct li element has an active class, but also ensure the "Home" li element does not:

1$this->get(route('about'))
2 ->assertOk()
3 ->assertElementExists('nav > ul', function(AssertElement $ul) {
4 $ul->contains('li', [
5 'class' => 'active',
6 'text' => 'About'
7 ]);
8 $ul->doesntContain('li', [
9 'class' => 'active',
10 'text' => 'Home'
11 ]);
12 });

The snippet illustrates the granular control provided by this package, including testing DOM elements, nested elements, forms, and more. At the time of the writing, this package's main assertions include:

  • Assert if an element exists
  • Assert if an element has a given attribute
  • Assert if an element contains in another element
  • Assert that an element does not contain another element
  • Find an element to process further assertions
  • Assert if a form exists
  • Assert that a form has a CSRF token
  • Assert for select options

You can learn more about this package, get full installation instructions, and view the source code on GitHub.

As a side note, this package's source code has an example of using the macroable mixin method to add multiple macro methods into another object from a service provider, which might be a helpful inspiration for others writing packages for Laravel.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.