oze*_*enK 9 testing reactjs jestjs react-testing-library
有没有办法使用 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>
)
}
Run Code Online (Sandbox Code Playgroud)
正则表达式:^\/.*\/$
测试 :
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()
})
Run Code Online (Sandbox Code Playgroud)
但 Jest 不接受我的正则表达式:
-- output :
Expected the element to have attribute:
href=/^\/.*\/$/
Received:
href="/link-1/"
Run Code Online (Sandbox Code Playgroud)
oze*_*enK 17
得到它使用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()
})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6625 次 |
最近记录: |