Skip to content

Treat <br/> as a whitespace for toHaveTextContent() #305

Open
@srittau

Description

@srittau

Describe the feature you'd like:

Suppose you want to match text from a paragraph containing <br/> elements for custom line break handling:

const MyGreatTextComponent = () => {
    return (
        <p>
            This is text
            <br/>
            with multiple lines.
            <br/>
            In reality, we'd have some dynamic data here.
        </p>
    )
}
test("", () => {
    render(<MyGreatTextComponent/>);
    expect(document.body).toHaveTextContent(/This is text with multiple lines/);
});

This test will fail, since the <br/> element will get stripped, without adding whitespace. The matcher sees This is textwith multiple lines.In reality [...]. In my opinion, it would be preferable, if <br/> elements would be considered whitespace for the .toHaveTextContent() matcher. As in the example, <br/> is usually used in place of a whitespace character and could be replaced with a space for the same semantic content.

Of course, changing the matcher to treat <br/> elements as space is a behavior change that could break existing tests.

Describe alternatives you've considered:

Currently, we are adding extra forced spaces {" "} before <br/> elements. That works, but is a neither obvious, nor useful for the implementation.

Teachability, Documentation, Adoption, Migration Strategy:

I am not too familiar with testing library's migration strategies, but in my opinion, this change would at least require a major version bump, due to the possibility of breaking existing tests relying on the current behavior. On the other hand, I believe this behavior would actually ease teachability, since it conforms closer to what a human user sees on the screen and is therefore closer to the expected behavior.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions