首页 > 解决方案 > 赛普拉斯:使用 trim() 或类似的东西测试 2 个元素是否相同

问题描述

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

 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);
     });
 });

问题是当我在要测试的组件中添加更长的 < td > 时,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:4000 毫秒后重试超时:预期 <td> 有文本“0.2”,但文本为“0.2”

标签: unit-testingtestingcypresse2e-testingcypress-component-test-runner

解决方案


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

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())
        })
    })
})

推荐阅读