Description
Describe the feature you'd like:
It would be nice to be able to add a typeguard to query options.
My use case (and I imagine it's a common one) is to assert that the element I am querying for is of a particular type. Currently, I do this with a separate check:
const { getByLabelText } = render(<MyComponent />)
const myCheckbox = getByLabelText('Checkbox Label') // returns type `HTMLElement`
// I need to assert that it is actually an HTMLInputElement, otherwise typescript
// complains about the assertion below, "property 'checked' does not exist on type 'HTMLElement'
if (!(myInput instanceof HTMLInputElement)) {
throw new Error('Selected input is not an input')
}
expect(myCheckbox.checked).toBe(true)
It would be nice to have a simple built-in way to tell Typescript that we're definitely getting an HTMLInputElement
(or any other specified type)
Suggested implementation:
possibly:
const myCheckbox = getByLabelText(
'Checkbox Label',
{
instanceOf: HTMLInputElement
}
)
Or, more flexible yet more verbose:
const inputTypeguard = (el: HTMLElement): el is HTMLInputElement => el instanceof HTMLInputElement
const myCheckbox = getByLabelText(
'Checkbox Label',
{
typeguard: inputTypeguard
}
)
I believe I have the chops to implement this if it is something that is worth adding!
Describe alternatives you've considered:
So far, I've just been writing my own helper functions for this
Teachability, Documentation, Adoption, Migration Strategy:
Teachability, Documentation, Adoption: This would be a helper for those using Typescript, the docs would need to explain this in the options
API for each ByXXX
query.
Migration: Should not present any problems as it would be adding an optional argument to the options.