【问题标题】:Cypress: test if 2 elements are the same using trim() or something similar赛普拉斯:使用 trim() 或类似的东西测试 2 个元素是否相同
【发布时间】:2021-11-15 23:00:04
【问题描述】:

我有一个测试,它获取表格的元素并通过查看它们的内容是否相同来对抗它们,并且它有效:

 cy.compareInputToText(
  'app-myTable table tbody > :nth-child(1) > :nth-child(2) > input',
  'app-myTable table tbody > :nth-child(1) > :nth-child(3)'
 );

 Cypress.Commands.add('compareInputToText', (inputSelector, textSelector) => {
   cy.get(inputSelector)
     .invoke('val')
     .then(currentValue => {
       cy.get(textSelector)
         .should('have.text', currentValue);
     });
 });

问题是当我在要测试的组件中添加一个较长的

时,html 编译器会自动换行,因此在测试中它会给我一个错误,因为当它换行时就像添加了一个空格... 我用trim 尝试了各种解决方案,如下所示:
   Cypress.Commands.add('compareInputToText', (inputSelector, textSelector) => {
        cy.get(inputSelector)
        .invoke('val')
        .then(currentValue => {
        cy.get(textSelector)
         .should('have.text', currentValue!.toString.trim());
     });
   });

但它不起作用。
错误:
错误:AssertionError: Timed out retrying after 4000ms: expected to have text '0.2', but the text is '0.2'

【问题讨论】:

    标签: unit-testing testing cypress e2e-testing cypress-component-test-runner


    【解决方案1】:

    根据您的错误消息,您的页面似乎有一个额外的空间,所以我认为您必须添加一个空间来代替修剪。

    Cypress.Commands.add('compareInputToText', (inputSelector, textSelector) => {
      cy.get(inputSelector)
        .invoke('val')
        .then((currentValue) => {
          cy.get(textSelector).should('have.text', currentValue + ' ')
        })
    })
    

    或者只是让文本从两者中删除空格然后断言,例如:

    Cypress.Commands.add('compareInputToText', (inputSelector, textSelector) => {
      cy.get(inputSelector)
        .invoke('val')
        .then((currentValue) => {
          cy.get(textSelector)
            .invoke('text')
            .then((text) => {
              expect(text.trim()).to.equal(currentValue.trim())
            })
        })
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-01
      • 2023-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多