首页 > 解决方案 > React 测试库:检查属性是否匹配正则表达式

问题描述

RTL 有没有办法测试元素是否具有基于正则表达式的有效属性?

在我的情况下,我想检查每个<a> 标签是否都有一个href带有斜杠和尾随斜杠 /的,如下所示:<a href="/link-1/">Link 1/</a>

零件 :

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>
  )
}

正则表达式:^\/.*\/$

测试 :

 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()
  })

但是 Jest 不接受我的正则表达式:

-- output :

Expected the element to have attribute:
href=/^\/.*\/$/
Received:
href="/link-1/"

标签: reactjstestingjestjsreact-testing-library

解决方案


得到它使用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()
  })

推荐阅读