Skip to content

[DX] Add new methods to DomCrawler to simplify some functional tests #11470

@javiereguiluz

Description

@javiereguiluz

The problem

The whitespace inside the HTML contents makes some functional tests harder than
they should be. Consider that you want to check the contents the following
element:

<p>
    Lorem ipsum
</p>

This test will fail:

$this->assertEquals(
    'Lorem ipsum',
    $crawler->filter('p')->first()->text()
);

You can obviously apply the trim() function, but this solution feels
unnatural:

$this->assertEquals(
    'Lorem ipsum',
    trim($crawler->filter('p')->first()->text())
);

The problem is worse when dealing with spaces and newlines:

<p>
    Lorem ipsum
    dolor sit
    amet
</p>

This solution no longer works:

$this->assertEquals(
    'Lorem ipsum dolor sit amet',
    trim($crawler->filter('p')->first()->text())
);

The solution

DomCrawler component could add two new methods called trim() and flatten().
The first one is equivalent to the PHP's trim() function:

<p>
    Lorem ipsum
</p>
$this->assertEquals(
    'Lorem ipsum',
    $crawler->filter('p')->first()->text()->trim()
);

The second one would also remove new lines and trim two or more spaces between
lines:

<p>
    Lorem ipsum
    dolor sit
    amet
</p>
$this->assertEquals(
    'Lorem ipsum dolor sit amet',
    $crawler->filter('p')->first()->text()->flatten()
);

My questions: is it worth it adding these two helper methods? Should I instead
create better tests? Can you think of a better solution to solve this problem?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions