testing-library / react-testing-library

🐐 Simple and complete React DOM testing utilities that encourage good testing practices.
https://testing-library.com/react
MIT License
18.97k stars 1.1k forks source link

Generics not supported when using bound functions #1303

Open JohnMarsden24 opened 5 months ago

JohnMarsden24 commented 5 months ago

Describe the feature you'd like:

Happy to give this a try myself!

I've found myself repeating the same pattern of typecasting elements returned from queries when using render when I need to access specific element properties as the return type for queries is always HTMLElement as seen in the two below screenshots:

Screenshot 2024-04-21 at 19 10 59 Screenshot 2024-04-21 at 19 12 54

Suggested implementation:

Firstly I thought about using function overloads and literal types to fix this problem but then realised any HTML element can be assigned a role so I then thought about using generics and came across this old issue which was implemented several years ago. In that thread it said the generics got lost when using screen, which was addressed and fixed but it looks like the same problem applies to render.

I imagine the fix will be similar to that found when adding generics to screen queries

Describe alternatives you've considered:

Open to suggestions

Teachability, Documentation, Adoption, Migration Strategy:

Allow users to pass generics to queries returned from render:

Screenshot 2024-04-21 at 21 34 23
syi0808 commented 3 months ago

I think this will be solved by importing a screen object.

import { screen } from 'react-testing-library';

expect(screen.getByRole<HTMLAnchorElement>('link').href).toEqual(...);