Summer sale! Save 50% on access to our entire library of courses.Join here →

How to Assert Element Count With Laravel Dusk

May 24th, 2024

While Dusk doesn't provide a direct assertion method to check the count of elements on a page, we can still fetch all elements by a selector and then make an assertion on what's returned.

Here's a simple test I created to check that search results on Codecourse appear in the correct order and have an initial limit of 9.

it('displays an initial set of courses in desc order by created date', function () {
    $course = Course::factory()
        ->create(['title' => 'Search for me', 'created_at' => now()->addHour()])
        ->searchable();

    $this->browse(function (Browser $browser) {
        $browser->visit('/search')
            ->waitFor('.search-wrapper');

        // How do we find the element count with Dusk?
    });
});

Luckily, Dusk has an elements method which returns an array of Facebook\WebDriver\Remote\RemoteWebElement instances.

This means we just do this to fetch all elements under a selector.

$results = $browser->elements('.search-item-course');

Combining this with our test, we can now assert the count of elements and pluck specific elements from the array to check them (e.g., making sure the first result in that list is the latest course).

it('displays an initial set of courses in desc order by created date', function () {
    $course = Course::factory()
        ->create(['title' => 'Search for me', 'created_at' => now()->addHour()])
        ->searchable();

    $this->browse(function (Browser $browser) {
        $browser->visit('/search')
            ->waitFor('.search-wrapper');

        $results = $browser->elements('.search-item-course');

        expect(collect($results))
            // Check that the first item in search is the latest course
            ->first()->getText()->toContain('Search for me')
            // Check that the total amount of results shown initially is 9
            ->count()->toBe(9);
    });
});

The getText method in the assertion above comes from the RemoteWebElement instance, which also provides a bunch of other helpful methods you can use if Dusk doesn't offer assertions for these out of the box.

Thanks for reading! If you found this article helpful, you might enjoy our practical screencasts too.
Author
Alex Garrett-Smith
Share :

Comments

No comments, yet. Be the first to leave a comment.

Tagged under