Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Testing Library : check if attribute matches regex

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/"
like image 274
ozenK Avatar asked Feb 21 '26 19:02

ozenK


1 Answers

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()
  })
like image 72
ozenK Avatar answered Feb 24 '26 09:02

ozenK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!