如何在JavaScript中读取包含星号文本的按钮?
解决通过含星号文本定位元素的问题
如果使用getByText直接传入带星号的字符串无法定位元素,可按以下方式处理:
正则匹配(推荐):星号在正则中是特殊字符,需转义后使用正则表达式匹配:
const readButton = test.getByText(/Read the rules \*/);检查DOM实际文本:确认星号是否属于元素的真实文本内容。如果星号是通过CSS伪元素(如
:after)添加的视觉效果,实际文本中并不包含星号,此时直接匹配核心文本即可:const readButton = test.getByText('Read the rules'); // 或结合元素角色/属性更精准定位 const readButton = test.getByRole('button', { name: 'Read the rules' });模糊匹配:若测试库支持(如React Testing Library),可关闭精确匹配选项来匹配包含目标文本的元素:
const readButton = test.getByText('Read the rules', { exact: false });
内容的提问来源于stack exchange,提问作者Sujatha Girijala
相关产品推荐
相关产品推荐

