testing-library / cypress-testing-library

🐅 Simple and complete custom Cypress commands and utilities that encourage good testing practices.
http://npm.im/@testing-library/cypress
MIT License
1.8k stars 152 forks source link

Add ability for users to supply generic type #258

Open samtsai opened 1 year ago

samtsai commented 1 year ago

What: Add ability to supply generic types similar to Cypress's API

Why:

This allows for further narrowing elements returned by queries in tests instead of just HTMLElement for every element

How:

Update types to include generic <E extends Node = HTMLElement> Ran npx dslint types locally and validated ExpectType tests still passed

Checklist:

samtsai commented 1 year ago

Not sure who maintains this project but wanted to get some 👀 on this PR

cc @kentcdodds @MichaelDeBoey @NicholasBoll

kentcdodds commented 1 year ago

I'm not sure I'm in favor of this change. This is one of those situations where you're letting the compiler lie to you. I would much rather you add a type guard (instanceof) or a cast (as), than hide that away in an abstraction.

samtsai commented 1 year ago

I'm not sure I'm in favor of this change. This is one of those situations where you're letting the compiler lie to you. I would much rather you add a type guard (instanceof) or a cast (as), than hide that away in an abstraction.

Yea I'm glad you called it out. I was following the pattern in Cypress itself but actual type guards would be useful. Let me consider this more.

It's also the same way we define it in DOM Testing Library: https://github.com/testing-library/dom-testing-library/blob/main/types/queries.d.ts#L5

Adding type guards as far as I can tell will require an API change to all the queries, something like this looks appealing: https://effectivetypescript.com/2020/07/27/safe-queryselector/

Still researching but haven't found many great examples in the wild, maybe because it's sort of straightforward?