cypress.io迭代元素列表以查看是否不存在文本,然后执行操作以添加元素
我正在尝试在列表上迭代(< ul>),以查看< li> li>列出项目元素。如果不存在字符串(柠檬),则我想执行一个操作以添加元素。否则,如果字符串确实存在,那么我只想什么都不做并继续。
示例html:
<ul id=theTree>
<li>Apple</li>
<li>Pear</li>
<li>Orange</li>
</ul>
我尝试过:
let found = false
cy.get('#theTree').find('li').each( ($node, i, $list) => {
if ($node.textContent.includes("Lemon")) {
found = true
}
})
// At this point after each <li> has been iterated over, will 'found' be true or false?
if (!found) {
// Add "Lemon" to the list here if it was not found in the <ul> list...
} else {
// Do nothing. Lemon already exists in the list.
}
if条件“ $ node.textcontent”正在返回未定义,而不是从列表元素返回文本内容。因此,.includes()函数会引发错误。
另外,我感觉到来自.east()的异步回调函数需要保存“找到= true”状态的诺言或其他方法,因此,第二个如果块可以正确确定是否找到了“柠檬”列表迭代。
任何帮助都非常感谢。
I'm trying to iterate over a list (<UL>) to see whether or not a specific string exists within the <li> list item elements. If the string (Lemon in this example) does not exist then I want to perform an action to add the element. Otherwise, if the string does exist then I just want to do nothing and continue on.
Sample html:
<ul id=theTree>
<li>Apple</li>
<li>Pear</li>
<li>Orange</li>
</ul>
I have tried:
let found = false
cy.get('#theTree').find('li').each( ($node, i, $list) => {
if ($node.textContent.includes("Lemon")) {
found = true
}
})
// At this point after each <li> has been iterated over, will 'found' be true or false?
if (!found) {
// Add "Lemon" to the list here if it was not found in the <ul> list...
} else {
// Do nothing. Lemon already exists in the list.
}
The if condition "$node.textContent" is returning undefined and not returning the text content from the list elements. Therefore, the .includes() function throws an error.
Also, I have feeling the asynchronous callback function from .each() needs a Promise or some other means of saving the "found = true" state, such that, the second if block can correctly determine whether or not "Lemon" was found in the list iteration.
Any help is very much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须在之后检查结果
每个
命令将被执行。例如,您可以使用
然后使用
命令如下:You have to check the result after the
each
command will be executed.For instance, you can use
then
command as follows:也许使用
.east()
迭代不是最简单的方法。使用
.then()
允许您传递找到的
对链条的值。如果您想在测试中以后使用它,也可以添加一个别名。设置命令链外部的变量称为“反弹”,可能会根据测试结构引起问题。
与别名
Perhaps iterating with
.each()
is not the easiest way to do this.Using
.then()
allows you to pass thefound
value down the chain. You could also add an alias if you want to use it later in the test.Setting a variable external to the command chain is called a "backflip" and can cause problems depending on the test structure.
With an alias