如何计算具有特定类名的元素的数量? [英] How to count the number of elements with a particular class name?
问题描述
如何使用夜表计数具有特定类名称的元素的数量?
How do I count the number of elements with a particular class name using nightwatch?
例如,我想计算页面上类名称为"sample"的元素的数量,并检查该数量是否大于8.如何使用夜表来做到这一点?
For example, I want to count the number of elements with class name "sample" on the page and check that the number if greater than 8. How can I do that using nightwatch?
推荐答案
假设您的页面包含此标记:
Assuming your page includes this markup:
<ul id="names">
<li>Stephanie</li>
<li>Luke</li>
<li>Marina</li>
</ul>
您可以执行以下操作:
module.exports = {
'Example test': browser => {
browser.url(browser.launchUrl);
browser.elements('css selector', '#names li', result => {
const numElements = result.value.length;
console.log(numElements);
});
}
}
请记住,您不能在该回调之外使用numElements
.从回调中返回它无济于事:browser.elements
忽略返回值.在回调之前初始化numElements
并在其内部设置 值对回调也无济于事:回调可能会运行得更晚.
Just bear in mind that you can't use numElements
outside of that callback. Returning it from the callback won't help: browser.elements
ignores the return value. Initializing numElements
before the callback and setting its value inside the callback won't help either: the callback might be run much later.
如果您确实需要在回调之外使用该值,则需要使用Promise
:
If you really need to use that value outside of the callback, you'll need to use a Promise
:
module.exports = {
'Example test': browser => {
browser.url(browser.launchUrl);
const numElementsPromise = new Promise(resolve => {
browser.elements('css selector', '#names li', result => {
resolve(result.value.length);
});
});
numElementsPromise.then(numElements => {
console.log(numElements);
});
}
}
这篇关于如何计算具有特定类名的元素的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!