首页 > 解决方案 > 量角器:如果列索引未知,如何在表中搜索?

问题描述

我的目标是确定在与确定的标题相对应的列中是否有一行包含文本。

这是视图:

<table>
  <headers>
    <header>Age</header>
    <header hidden="isSmallScreen()">Gender</header>
    <header>Size</header>
  <headers>
  <body>
    <row>
      <col>20</col>
      <col hidden="isSmallScreen()">F</col>
      <col>180</col>
    </row>
    <row>
      <col>21</col>
      <col hidden="isSmallScreen()">M</col>
      <col>185</col>
    </row>
  </body>
<table>

重要的是要知道应用程序是响应式的,这意味着如果屏幕很小,则第二列不在 DOM 中。

测试代码试图知道是否有人 size=180,并且无论屏幕尺寸如何,它都必须工作。

我正在使用打字稿。

const headers = element.all(by.tagName('header'));
let headerIndex: number;
headers.filter((header: ElementFinder, columnIndex: number) => {
        return header.getText().then(innerText: => {
            if (innerText === 'Size') {
                headerIndex = columnIndex;
            }
            return innerText === 'Size';
        });
    },
);
const rows = searchRowsByTextInColumn(headerIndex, 180);
expect(rows.count()).toBe(1);

该方法searchRowsByTextInColumn(headerIndex, searchText)已实现,在该级别没有问题。

问题是headerIndex调用searchRowsByTextInColumn(). 这很正常,因为它存在于异步代码中。

现在我该怎么做才能使搜索工作?

标签: protractor

解决方案


执行时searchRowsByTextInColumn(headerIndex, 180);,headerIndex 还没有完成赋值,因为element.all().filter()异步运行。

function findHeaderIndex(header) {
    return element.all(by.css('table > headers > header'))
         .getText().then(function(headers){
             return headers.indexOf(header);
    });
}    

function searchRowsByTextInColumn(header, cellText) {
    return findHeaderIndex(header).then(function(index) {
        var xpath = util.format('//table/body/row[ col[%s][text()="%s"] ]',
                                index, cellText);
        return element.all(by.xpath(xpath));
    });
}

searchRowsByTextInColumn('size', 180).then(function(rows){
    expect(rows.count()).toBe(1);
    // if above expect not work, try below

    rows.count().then(function(rowCount){
        console.log('rowCount: ' + rowCount);
        expect(rowCount)).toBe(1);
    });           
});

推荐阅读