有没有其他方法可以检查所有子项显示的文本是否不同?

Is there any alternative to check if the text displayed of all the children are different?

提问人:iro 提问时间:1/1/2023 最后编辑:iro 更新时间:1/3/2023 访问量:109

问:

it('features', () => {
      home.featuresMainTitle("What you'll learn")
      cy.get('.grid').children().each(($el, index, $list) =>{
        const currentText = $el.find('h3').text()
        const nextText = $el.next().find('h3').text()
        expect(currentText).to.not.equal(nextText)
      })

我正在从 DOM 捕获网格,并试图验证网格的每个子项中的文本是否必须与其他子项不同。

代码可以工作,但它给我的印象是这很幼稚,并且有一种更好的方法来使用更完善的代码来实现相同的结果,避免使用该 javascript 变量(currentText 和 nextText)。也许有一种我不知道的柏树特性,乍一看可以使线条更干净。

JavaScript 变量 Cypress Equality Children

评论

2赞 Bergi 1/1/2023
请不要发布代码绘画的链接
0赞 iro 1/2/2023
感谢您的建议 Bergi,这是我的第一篇文章,我还是一个小手

答:

1赞 jjhelguero 1/1/2023 #1

另一种方法是,获取所有子数组,提取它们的文本,从新集合创建一个数组,然后检查它是否等于原始数组。

cy.get(".grid")
  .children()
  // get innerText of all children
  .then(($el) => Cypress._.map($el, (el) => el.innerText))
  .then((childrenText) => {
    // create new array of unique values
    const uniqueText = Array.from(new Set(childrenText));
    expect(childrenText).to.deep.equal(uniqueText);
  })

下面是一个工作示例

3赞 Lola Ichingbola 1/1/2023 #2

不是真的减少了代码,而是给了你一个更强大的测试:

如果使用 Set,则可以验证 Set 的长度和长度。.children()

Set 对象允许您存储任何类型的唯一值

这并不限制您比较下一个和当前,而是比较所有子项。

cy.get(".grid").children()
  .then($els => {
    const setOfTexts = new Set();
    [...$els].forEach(el => setOfTexts.add(el.innerText)); // only stores unique values
    return setOfTexts;
  })
  .then(setOfTexts => {
     cy.get(".grid").children().its('length')
       .should('eq', setOfTexts.size)
  })

或用减速机,

cy.get(".grid").children()
  .then($els => [...$els].reduce((acc, el) => {
    acc.add(el.innerText)
  }, new Set()))
  .then(setOfTexts => {
     cy.get(".grid").children().its('length')
       .should('eq', setOfTexts.size)
  })
3赞 Paolo 1/1/2023 #3

在计算唯一值的相同想法上,使用 Lodash 方法uniqBy()

cy.get('.grid')
  .children()
  .should($els => {
    const unique = Cypress._.uniqBy($els, (el) => el.innerText)
    expect(unique.length).to.eq($els.length)
  })

这将通过网格中的所有文本都是唯一的。


考虑 <h3>

由于您在 中执行 ,因此这应该执行相同的操作,除非网格中有一些需要排除的内容。.find().each()<h3>

cy.get('.grid')
  .find('h3')
  .should($els => {
    const unique = Cypress._.uniqBy($els, (el) => el.innerText)
    expect(unique.length).to.eq($els.length)
  })