gpt4 book ai didi

javascript - Cypress - 包含文本和字符串结尾的属性

转载 作者:行者123 更新时间:2023-12-03 21:16:10 24 4
gpt4 key购买 nike

假设我有这样的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>

我想断言有一个带有href的项目,它以'/123'结尾。
const test_id = '123'

cy.get('.my_class').find('a').should("have.attr", "href").and("contain", '/' + test_id);


它有效,但是我不知道如何确保断言仅对具有精确结尾的 href 为真('/123',如第一个代码片段中的 #first_case 所示),并且对于以开头的其他字符串为假这样的数字,例如('/1234567',如第一个代码片段中的#second_case 所示)。

换句话说,断言对于#first_case 应该为真,而对于#second_case 则为假。

我尝试使用字符串结尾符号或制作新的 RegExp 对象,但无法使其工作。
任何帮助,将不胜感激!

最佳答案

.should()将为您提供 href,以便您可以在 .then() 中使用它随意阻止(见 https://stackoverflow.com/a/48451157/2883129 ),所以你可以使用 .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;
});

或者为了让它更易读,失败信息更清晰,你可以使用 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);
});

关于javascript - Cypress - 包含文本和字符串结尾的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60489401/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com