reactjs - 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/"
解决方案
得到它使用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()
})
推荐阅读
- django - 子查询中的 Django 回合
- linux - 当文件内容为参数时,为文件中的每一行运行命令
- python - 计算器的最佳 python 模块
- apache-spark - 将字符串类型转换为pyspark中的行
- python - 在 Python 中访问其范围之外的函数的局部变量
- django - Django 最佳实践
- javascript - 带有 knex 和 node.js 的嵌套数组
- reactjs - React Material UI 开关标签放置
- google-cloud-platform - 如何增加 Google Cloud GPU 配额
- python - 如何仅使用 numpy 预处理文本