P D*_*P D 6 javascript cypress
让我们假设我有这样的 html:
<div class="my_class" id="first_case">
<a href="/foo/bar/123"></a>
</div>
<div class="my_class" id="second_case">
<a href="/foo/bar/1234567"></a>
</div>
Run Code Online (Sandbox Code Playgroud)
我想断言有一个带有href 的项目,它以'/123' 结尾。
const test_id = '123'
cy.get('.my_class').find('a').should("have.attr", "href").and("contain", '/' + test_id);
Run Code Online (Sandbox Code Playgroud)
它有效,但是我不知道如何确保断言仅适用于具有精确结尾的 href('/123',如第一个代码片段中的#first_case 所示),并且对于以开头的其他字符串为假例如('/1234567',如第一个代码片段中的#second_case 所示)。
换句话说,断言对于#first_case 应该是正确的,但对于#second_case 应该是错误的。
我尝试使用字符串结尾符号或创建新的 RegExp 对象,但无法使其工作。任何帮助,将不胜感激!
.should()将为您提供 href,以便您可以在.then()块中使用它(请参阅/sf/answers/3391581021/),因此您可以使用.endsWith():
const test_id = '123'
cy.get('.my_class')
.find('a')
.should("have.attr", "href")
.then(href => {
expect(href.endsWith(test_id)).to.be.true;
});
Run Code Online (Sandbox Code Playgroud)
或者为了使其更具可读性并使失败消息更清晰,您可以使用https://www.chaijs.com/plugins/chai-string/:
const test_id = '123'
cy.get('.my_class')
.find('a')
.should("have.attr", "href")
.then(href => {
expect(href).to.endWith(test_id);
});
Run Code Online (Sandbox Code Playgroud)
我认为还有更简单的方法可以做到这一点。您可以使用 singlecy.get()和 single,should()因为 Cypress 选择器的行为方式应与 jQuery 选择器相同。
cy.get('.my_class a[href$="/123"]').should('have.length', 1);
Run Code Online (Sandbox Code Playgroud)
$=将仅匹配以 结尾的属性/123。
在 vanilla JS 中,您可以尝试使用querySelector()选择器( )结尾的属性[name$="value"。请注意,您忘记关闭该a元素。
const test_id = '123'
var el = document.querySelector(`[href$="${test_id}"]`);
console.log(el);Run Code Online (Sandbox Code Playgroud)
<div class="my_class" id="first_case">
<a href="/foo/bar/123"></a>
</div>
<div class="my_class" id="second_case">
<a href="/foo/bar/1234567"></a>
</div>Run Code Online (Sandbox Code Playgroud)