首页 > 解决方案 > 赛普拉斯检查正文中不存在字符串,不包括块或 div

问题描述

我有一系列字符串来检查它们是否存在于各个页面中;但我不想检查单个 div。

我有几个页面可以检查字符串“迈阿密”、“坦帕”、“那不勒斯”、“奥兰多”是否不存在,但我div在每个页面的底部都有一个包含

<div class="footer"><h3 class="availability">
                 We are also available in
            </h3> <a href="..." class="province">
                Miami
            </a><a href="..." class="province">
                Tampa
            </a><a href="..." class="province">
                Naples
            </a><a href="..." class="province">
                Orlando
            </a>
</div>

我创建了一个在每个页面中循环的测试并检查

cy.get('body').should('not.contain', 'Miami')
cy.get('body').should('not.contain', 'Tampa')
cy.get('body').should('not.contain', 'Naples')
cy.get('body').should('not.contain', 'Orlando')

但是这些测试显然失败了,因为 cypress 在其中找到了那些字符串div

有没有办法从搜索中排除它?我试过

cy.get('body')
    .not('footer')
    .should('not.contain', 'Miami')

但这不起作用!

作为一种解决方法,我认为我可以从 dom 中删除 div,但我不确定这是否是个好主意,无论如何我不知道如何在 cypress 中做到这一点。

标签: javascriptcypress

解决方案


cy.get().not()命令不经常看到,但文档说

.filter() 的对面

哪种方法 *取出所有在 中找到的元素get()并过滤掉任何与.not().

所以在

cy.get('body')
  .not('.footer')                     // no class footer on body, no effect
  .should('not.contain', 'Miami')     // fails because not.contain is recursive

body没有.footer,所以什么都没有被过滤掉。

下一步.should('not.contain'搜索 的所有子级body,其中包括.footer,因此未通过测试。

如果页脚是 的直接子body,则可以添加 a.children()使其工作

<body>
  <div>NYC</div>
  <div class="footer">Miami</footer>
</body>  
cy.get('body')
  .children()                        // direct descendants only
  .not('.footer')                    // now .footer is excluded
  .should('not.contain', 'Miami')    // passes

或使用相反的逻辑

cy.get('body')
  .find('.footer')
  .siblings()
  .should('not.contain', 'Miami')

如果正文和页脚之间存在一个或多个级别,则需要正确定位级别

<body>
  <div class=""wrapper1">
    <div class=""wrapper2">
      <div>NYC</div>
      <div class="footer">Miami</footer>
    </div>
  </div>
</body>  
cy.get('body')
  .children()                        // wrapper 1
  .children()                        // wrapper 2
  .children()
  .not('.footer')                    // .footer is excluded
  .should('not.contain', 'Miami')    // passes

但这开始看起来很混乱,如果结构发生变化,它就会变得脆弱。

基本问题是它.not()不是递归的,而是.should('not.contain', 'Miami')递归的。可行的是非递归文本检查器。

这是我能想到的最强大的方法

cy.get('body')
  .find('*')                                    // children of body - recursive
  .not('.footer')                               // exclude the footer
  .each($el => {                   
    cy.wrap($el.contents().get(0).textContent)  // text of this element only (not children)
      .should('not.contain', 'Miami')           // passes
  })

在哪里

$el.contents()     // list of element and all child nodes
   .get(0)         // filter just the parent
   .textContent    // get it's text

推荐阅读