检查元素是否有孩子

时间:2019-10-25 14:19:05

标签: html testing automated-tests e2e-testing testcafe

我有以下DOM树(简化了)

<div class=row-0>...</div>
<div class=row-1>
  <div class=container>
    <div class=panel>...</div>
  </div>
</div>
<div class=row-2>...</div>
<div class=row-3>
  <div class=container>
    <div class=panel>...</div>
    <div class=drawer>...</div>
  </div>
</div>
<div class=row-4>...</div>

如您所见,所有元素都有一个面板class=panel,但并非所有元素都有一个抽屉class=drawer。 我正在遍历以下元素:

const events = Selector('[class^="row-"]');
const eventCount = await events.count;

for (let i = 0; i < eventCount; i++) {
  const event = await events.nth(i);
  // Here's where I want to check if the event (class=row-x) has a child element class=drawer
  const drawer = await Selector(event).child('class["drawer"]')
  if (await drawer.exists) {
    console.log('Found drawer')
  }
}

我可以成功遍历所有行,但是我无法检测到某个事件是否具有抽屉。我尝试遵循this答案和docs的逻辑。

如何执行此逻辑?

1 个答案:

答案 0 :(得分:1)

我建议您按照以下方式重写测试:

  1. 获取所有“抽屉”元素:Selector('div.drawer')
  2. 根据您的页面层次结构获取包含“抽屉”元素的所有行。

我创建了一个简单的示例-请查看以下示例:

index.html

<html>
<head></head>
<body>
<div class=row-0>Row 0</div>
<div class=row-1>
    Row 1
    <div class=container>
        <div class=panel>...</div>
    </div>
</div>
<div class=row-2>Row 2</div>
<div class=row-3>
    Row 3
    <div class=container>
        <div class=panel>...</div>
        <div class=drawer>...</div>
    </div>
</div>
<div class=row-4>Row 4</div>
<div class=row-5>
    Row 5
    <div class=container>
        <div class=panel>...</div>
        <div class=drawer>...</div>
    </div>
</div>

</body>
</html>

test.js

import { Selector } from 'testcafe';

fixture `Fixture`
    .page `./index.html`;

test('find rows with "drawer"', async t => {
    const drawerElements = Selector('div.drawer').addCustomDOMProperties({
        outerHTML: el => el.outerHTML
    });
    const length = await drawerElements.count;

    console.log('Row elements count:', length);

    for (let i = 0; i < length; i++) {
        console.log('//', i + 1, 'element:');
        console.log(await drawerElements.nth(i).parent().parent().outerHTML);
    }
});

命令:

testcafe chrome test.js

结果:

 Running tests in:
 - Chrome 78.0.3904 / Windows 10.0.0

 Fixture
Row elements count: 2
// 1 element:
<div class="row-3">
    Row 3
    <div class="container">
        <div class="panel">...</div>
        <div class="drawer">...</div>
    </div>
</div>
// 2 element:
<div class="row-5">
    Row 5
    <div class="container">
        <div class="panel">...</div>
        <div class="drawer">...</div>
    </div>
</div>
 √ find rows with "drawer"


 1 passed (1s)