【问题标题】:Cypress: how to check if a string interpolation contains any value from an array赛普拉斯:如何检查字符串插值是否包含数组中的任何值
【发布时间】:2021-10-24 13:43:18
【问题描述】:

我想知道解决这个问题的最佳方法:

  • 我有多个要遍历的 DOM 元素,除了角色名称之外,它们都有相同的 src 路径。
  • 我想验证每个 src 是否与数组中的任何玩家名称值匹配

const playerName = ["_player_One_", "_player_two_", "_player_three_", "_player_four_"]

    cy.get("myElement").each(($match) => {
        cy.wrap($match).each(($el) => {

            cy.get($el).should("include.attr", "src", `/foo/bar/art/all-art-${playerCharacter[]}.png`);
        });
    });

我知道它的当前形式,我将返回整个数组输出,但我只是分享我来自的角度以供参考。

任何帮助都将不胜感激,即使这是我没有考虑过的一种新的结构方式。

提前致谢!

【问题讨论】:

    标签: javascript html arrays loops cypress


    【解决方案1】:

    将玩家名称转换为链接数组,使用 'oneOf' 断言。

    在玩家的元素改变顺序时有效。

    const players = ["_player_One_", "_player_two_", "_player_three_", "_player_four_"]
    
    const links = players.map(player => `/foo/bar/art/all-art-${player}.png`)
    
    
    it('all elements have a player', () => {
    
      cy.get('div[src^="/foo/bar/art/all-art-"]')
        .each($el => {
          cy.wrap($el).invoke('attr', 'src').should('be.oneOf', links)
        })
    })
    
    
    it('all players have an element', () => {
    
      cy.get('div[src^="/foo/bar/art/all-art-"]')
        .then($els => {
          const attrLinks = [...$els].map($el => Cypress.$($el).attr('src'))
          links.forEach(link => {
            cy.wrap(link).should('be.oneOf', attrLinks)
          })
        })
    })
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      const playerName = ["_player_One_", "_player_two_", "_player_three_", "_player_four_"]
      
      cy.get('myElement').each(($ele, index) => {
        expect($ele.attr('src')).to.include(playerName[index])
      })
      

      【讨论】:

        猜你喜欢
        • 2015-02-28
        • 2018-10-12
        • 2013-11-12
        • 1970-01-01
        • 2012-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多