Is there a way with RTL to test if an element has a valid attribute based on a regex ?
In my case I'd like to check if every <a> tag has a href with forward and trailing slashes / like so : <a href="/link-1/">Link 1/</a>
Component :
const DropdownMenu = ({ open }) => {
return (
<ul className="dropdown-menu">
{open && (
<>
<li>
<Link to="/link-1/">Link 1</Link>
</li>
<li>
<Link to="/link-2/">Link 2</Link>
</li>
<li>
<Link to="/link-3/">Link 3</Link>
</li>
</>
)}
</ul>
)
}
Regex : ^\/.*\/$
Test :
test('links have forward and trailing slashs', () => {
render(<DropdownMenu open={true}></DropdownMenu>)
const listLinks = screen.getAllByRole('link')
listLinks.forEach((el) => {
expect(el).toHaveAttribute('href', /^\/.*\/$/)
})
screen.debug()
})
But Jest doesn't take my regex :
-- output :
Expected the element to have attribute:
href=/^\/.*\/$/
Received:
href="/link-1/"
Got it using expect.stringMatching(string | regexp)
test('links have beginning and trailing slashes', () => {
render(<DropdownMenu open={true}></DropdownMenu>)
const listLinks = screen.getAllByRole('link')
listLinks.forEach((el) => {
expect(el).toHaveAttribute('href', expect.stringMatching(/^\/.*\/$/))
})
screen.debug()
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With