Description
Describe the feature you'd like:
Ability to find elements from a rendered DOM by some sort of CSS selector, a la jQuery.
For example, I have this DOM:
<button disabled="" type="button" class="ant-btn ant-btn-primary ant-btn-circle ant-btn-icon-only"><i class="anticon anticon-plus"><svg viewBox="64 64 896 896" class="" data-icon="plus" width="1em" height="1em" fill="currentColor" aria-hidden="true"><path snip></path></svg></i></button>
It's a <Button/>
component from Ant Design but not important.
Now of the existing methods allow me to get this DOM element. I could modify the main code and inject a data-testid="add-button"
and then use getByTestId
but then it feels like the code has to work for the tests rather than the other way around.
Suggested implementation:
const { getByCSSSelector } = render(<Button disabled={false} icon="plus"/>)
fireEvent(getByCSSSelector('button')).click()
// or...
console.log(getByCSSSelector('button i.anticon'))
// or...
console.log(getByCSSSelector('button i svg'))
Describe alternatives you've considered:
Another challenge I found was I was trying to see if a DOM element existed based on it's classList
. The DOM element, when rendered would (depending on business logic) set (or not set) className="spin-animation"
.
Then I'd be able to do:
const { getByCSSSelector } = render(<MyComponent key={value}/>)
expect(getByCSSSelector('div.spin-animation')).toBeInTheDocument()
Teachability, Documentation, Adoption, Migration Strategy:
No migration needed. A better name that CSSSelector
maybe. Perhaps just querySelector
or getBySelector
.