Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

jest-dom/prefer-to-have-text-content leads to unexpected behaviour #337

Open
darkowic opened this issue Nov 16, 2023 · 1 comment
Open
Labels
enhancement New feature or request help wanted Extra attention is needed

Comments

@darkowic
Copy link

  • eslint-plugin-jest-dom version: 5.1.0
  • node version: 18.14.2
  • npm version: yarn 3

Relevant code or config

What I wanted to use

            expect(
                screen.getByTestId('location')
            ). toHaveTextContent('/');

What I'm forced to use:

            // Can not use toHaveTextContent because it doesn't match exact text
            // eslint-disable-next-line jest-dom/prefer-to-have-text-content
            expect(
                screen.getByTestId('location')
                    .textContent
            ).toBe('/');

What you did:
I wanted to ensure that the tested value is exactly the value I pass to assertion.

What happened:
Eslint rule warns to use toHaveTextContent. Unfortunately, that change is also changing the behavior.

Problem description:
I believe everything is clear from the above examples and explanations. The jest-dom/prefer-to-have-text-content rule forces me to change my code to a version that doesn't fulfill my requirements.

Suggested solution:
The rule should only be triggered if the assertion toContain or similar is used.
Extend toHaveTextContent with exact option. Or add toBeTextContent.

@G-Rath
Copy link
Collaborator

G-Rath commented Feb 10, 2024

(I assume you've got your "wanted to use" and "forced to use" examples mixed up)

To do an exact match you want to use a regex, per the docs:

expect(element).toHaveTextContent(/^Text Content$/) // to match the whole content

so you want

            expect(
                screen.getByTestId('location')
            ). toHaveTextContent(/^\/$/);

Since toBe, toEqual, and toStrictEqual are exact matchers the autofix should ideally use a regex like this - it actually seems we try to do something like that but for toContain and toMatch; it might be that these logics just need inverting? (and it could be this came from the matcher originally being exact then was later changed)

@G-Rath G-Rath added help wanted Extra attention is needed enhancement New feature or request labels Feb 10, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

2 participants