如何从在testcafe中找到的多个匹配中首次出现元素 [英] How to get first occurrence of the element from multiple match found in testcafe

查看:140
本文介绍了如何从在testcafe中找到的多个匹配中首次出现元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些情况下,如果我评估Selenium xpath/locator可以看到多个节点匹配项.

There are cases where I can see multiple node matches found if I evaluate my Selenium xpath/locator.

示例://span [@ username ='xyz'](使用Selenium的示例代码)

Example: //span[@username='xyz'] ( sample code using Selenium )

如果上述相对路径与多个节点匹配(例如:找到了5个匹配节点.请在下面找到匹配节点的列表).

if the above relative path matches with multiple nodes (ex: 5 matching nodes found. Find the list of matching nodes below ).

在硒中,我可以这样使用:(//span [@ username ='xyz'])[1],它访问找到的5个匹配项中的第一个匹配项.

In selenium I can use like: (//span[@username='xyz'])[1] which accessing first match out of 5 matches found.

我们如何使用TestCafe实现相同的目标?

How we can achieve the same using TestCafe?

推荐答案

import { Selector } from 'testcafe';

fixture `fixture`
    .page('https://devexpress.github.io/testcafe/example/');

const elementByXPath = Selector(xpath => {
    const iterator = document.evaluate(xpath, document, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null )
    const items = [];

    let item = iterator.iterateNext();

    while (item) {
        items.push(item);
        item = iterator.iterateNext();
    }

    return items;
});

test('Click by first checkbox', async t => {
    const firstCheckboxSelector = Selector(elementByXPath('//input[@type="checkbox"]'));
    const secondCheckboxSelector = Selector(elementByXPath('//input[@type="checkbox"]')).nth(1);

    await t.click(firstCheckboxSelector);
}); 

这篇关于如何从在testcafe中找到的多个匹配中首次出现元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆