首页 > 解决方案 > 使用 TestCafe Selector 或 testcafe-react-selector 为嵌套组件查找元素节点时遇到问题

问题描述

我正在使用 TestCafe 1.1.0 版和 Testcafe-react-selector 3.1.0 版。我的目标是从节点返回文本。HTML 树如下所示:

<div class="header">
     <div class="title">board</div>
     <div class="secondary-title">Wednesday Mar 06, 2019</div>
</div>
<div class="MuiPaper-root-9 MuiPaper-elevation2-02 MuiPaper-rounded-9 board-title-break">
    <div class="board-header">
         <div class="title">Text Title</div>
         <div class="details">
           <div>
               <div>Total</div>
               <div class="header-count total">2 people</div>
           </div>
           <div> ... </div>
           <div> ... </div>
           <div> ... </div>
           ....
           </div>

在这里,我想获取“2 个人”文本并验证“2 个人”是否可见。

我尝试使用 Selector 如下:

Selector('.header-count total > div')

但这没有成功。

这是从 REACT chrome 扩展获得的同一 HTML 树的 React 树:

<TitleBreakdown loading={false} accountId={323}> ==$r
     WithStyles(Paper) className="title-breakdown">
          <Paper className="title-breakdown" component="div" elevation={2} square={false}>
              <div className="MuiPaper-root-9 MuiPaper-elevation2-02 MuiPaper-rounded-9"
                  <div className="board-header">
                      <div class="title">Text Title</div>
                      <div class="details">
                          <div>
                              <div>Total</div>
                              <div class="header-count total">2 people</div>
                          </div>
                          <div> ... </div>
                          <div> ... </div>
                          <div> ... </div>
                           ....
                          </div>

对于上面的 React 组件,我尝试使用它:

ReactSelector('TitleBreakdown').findReact('div').findReact('div').nth(1).findReact('div').nth(1).withKey('header-count total');

总之, Selector 和 ReactSelector 都对我不起作用,因为当我尝试断言元素时出现此错误:

Cannot obtain information about the node because the specified selector does not match any node in the DOM
  tree.

我知道我做错了什么,但无法弄清楚问题所在。有人可以告诉一个处理这些类型案件的好方法吗?

标签: javascriptreactjsautomated-testse2e-testingtestcafe

解决方案


更改Selector('.header-count total > div')Selector('div.header-count.total')。完整的断言看起来像:

await t
   .expect(Selector('div.header-count.total').innerText).eql('2 people');

它目前的编写方式,我相信你是在告诉 TestCafe 寻找一个元素div的子total元素,total也是.header-count. TestCafe 认为它正在寻找这种结构:

<div class="header-count">
   <total>
      <div>2 people</div>
   </total>
</div>

查看W3 Schools Selector Reference以了解每种模式选择的内容。


推荐阅读