Organizm238's avatar

Test order of elemets on page

Hi! I want to test whether my sorting works properly with Laravel TestCase. I have simple test page:

    <div id="values">
        @foreach(['Value1', 'Value2'] as $value)
            <div class="test-class">{{$value}}</div>
        @endforeach
    </div>

And now i want to test if the first .test-class element contains 'Value1'. I had tried different approaches, and had no success. Here are first one:

     public function testSorting()
    {
        $this->visit(route('dummy'));
        $this->see('Value1');
        $this->seeInElement('.test-class:first-of-type', 'Value2');
    }

This one resulted in exception:

    Symfony\Component\CssSelector\Exception\ExpressionErrorException: "*:first-of-type" is not implemented.

Then I tried

    $this->seeInElement('#values:first-child', 'Value2');

and my test when green. But it should be red, because first child is 'Value1'. It totally ignored ':first-child' part.

Then I tried

    $this->seeInElement('#values:nth-child(1)', 'Value2');

and got green too. So this approach doesn't work either.

Have I missed something? Or there is no way to test order of elements on page with Laravel tests?

0 likes
1 reply
Organizm238's avatar
Organizm238
OP
Best Answer
Level 8

So, i have solved it. The key was to look into \Symfony\Component\DomCrawler\Crawler class. It has a lot of useful methods like first(), last() or eq($number). I have created this helper method in my TestCase class:

    public function seeInFirstElement($selector, $text)
    {
        $this->assertContains($text, trim($this->crawler->filter($selector)->first()->text()));

        return $this;
    }

You can get rid of trim() function but with it the output looks better in case of failed test. So, in my tests I use such constructions to test ordering:

    $this->seeInFirstElement('.test-class', 'Value1');
1 like

Please or to participate in this conversation.