Home > database >  Cypress: test if 2 elements are the same using trim() or something similar
Cypress: test if 2 elements are the same using trim() or something similar

Time:09-23

I have a test that takes elements of a table and counters them by seeing if their content is the same, and it worked:

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

The problem is when I add a longer < td > in my component to be tested, the html compiler automatically wraps, and therefore in the test it gives me an error because when it wraps it's like adding a space...
I tried various solutions with the trim like this:

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

but it doesn't work.
The error:
Error: AssertionError: Timed out retrying after 4000ms: expected < td > to have text '0.2', but the text was ' 0.2 '

CodePudding user response:

As per your error message it seems that your page has an extra space, so instead trimming I think you have to add a space.

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

OR just get the texts remove spaces from both and then assert, something like:

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