赛普拉斯:不可见阵列的长度

时间:2021-06-10 04:27:01

标签: javascript html jquery arrays cypress

我知道这将是一个漫长的探索过程,对此我深表歉意。

TL:TR 我开始学习 Cypress,但偶然发现了一个问题。我得到了一个高度动态的列表(这意味着它可以并且它会不时有零个元素),我想知道它的长度以做出一些断言。问题是,当它有零个元素时,Cypress 会下降来获取这个 DOM 元素。 我不知道如何在尝试 .get() 之前断言数组是否为空。关于如何做到这一点的任何线索?提前致谢!

帖子

我想遵循这个逻辑检查一个项目是否被添加到列表中

  • 获取数组长度,保存到变量中。 (需要学习如何)
  • 添加一个项目(这没有任何问题)
  • 获取新的数组长度,进行比较。如果 new == old + 1,则添加。

HTML5(此代码在列表中一个项目)

<section id="main" style="display: block;">
  <input id="toggle-all" type="checkbox">
  <label for="toggle-all">Mark all as complete</label>
  <ul id="todo-list">
    <li>
      <div class="view">
        <input class="toggle" type="checkbox">
        <label>a</label>
        <button class="destroy"></button>
      </div>
      <input class="edit" value="a">
    </li>
  </ul>
</section> 

HTML5(此代码没有列表中的项目)

<section id="main" style="display: none;">
  <input id="toggle-all" type="checkbox">
  <label for="toggle-all">Mark all as complete</label>
  <ul id="todo-list"></ul>
</section>

柏树

cy.get('#todo-list').find('.view').each(($el, i) =>
{
  cont = i + 1;
  cy.log(cont);
})

这种方法显然行不通,原因有很多。首先,如果列表有零个元素,赛普拉斯找不到它,我无法继续。如果是这样,稍后进入 '>' 语句,我的 var cont 为 0。 我确定我搞砸了。

这是应用程序,因此您可以查看 html,我可以尽可能缩短这篇文章: Todo List

我也一直在尝试使用 footer > todo-count 元素的另一种方法,当列表中有一个元素时它正在工作。当我不这样做时,我的问题又出现了:

cy.get('#todo-count').then(($el1) =>{
  const prev = parseFloat($el1.text())
  cy.log(prev)

  {Here I add the item}

  cy.get('#todo-count').invoke('text').then(parseFloat).should('be.gt', prev)
})

同样,如果元素不可见,Cypress 将找不到它。用 $el.css('display') == 'block'.is(":visible") 试过 if/else,但我不明白。

2 个答案:

答案 0 :(得分:3)

我不知道页脚和#id-count 发生了什么,但不要使用它。自己计算元素

it('adds an item to the list', () => {

  cy.get('ul').then($list => {

    const initialCount = $list.find('li').length;
    expect(initialCount).to.eq(0)

    {Here add the item}

    // const afterAddingCount = $list.find('li').length;
    // expect(afterAddingCount).to.eq(1);

    // This is better
    cy.get('ul li')
      .should('have.length', 1);    // retry on this if animation, etc
     
  })
})

it('updates the todo-count display', () => {

  // show the HTML for the footer 
  // before and after adding an item
  // then can add a test here

})

答案 1 :(得分:2)

这就是我认为您应该测试列表计数器的方式

it('updates the todo-count display', () => {

  cy.get('#footer')
    .should('have.css', 'display', 'none')

  cy.get('#todo-count')
    .should('not.exist')                    // verify counter is not present

  // {Here add the item}

  cy.get('#footer')
    .should('have.css', 'display', 'block')

  cy.get('#todo-count')
    .should('exist')                       // now the counter exists
    .invoke('text')
    .should('include', '1')                // and its value is '1'
})