【问题标题】:React Testing Library : check if attribute matches regexReact 测试库:检查属性是否匹配正则表达式
【发布时间】:2021-07-14 15:32:06
【问题描述】:

有没有一种 RTL 方法来测试 element 是否具有基于正则表达式的有效 attribute

在我的情况下,我想检查每个 <a> 标签 是否有一个带有 forward尾部斜杠 @的 href 987654324@ 喜欢这样:<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/"

【问题讨论】:

标签: reactjs testing jestjs react-testing-library


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-12-16
    • 1970-01-01
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-22
    • 1970-01-01
    相关资源
    最近更新 更多