Asserting that an input element contains a specific value in Cypress

Viewed 13756

I am trying to assert the following where propSizeSel is the CSS selector to my numerical input element:

cy.get(propSizeSel).clear().type(100)
    .should('contain', 100);

Unfortunately, this assertion fails in the following manner despite the input element accepting the value of 100.

enter image description here

As you can see the input element has accepted the value 100 as expected:

enter image description here

Why is it that I can't seem to make this simple assertion?

2 Answers

Please try with 100 in single quotes and in the assert, please use should('have.value', '100') instead of contain;

cy.get('propSizeSel').clear().type('100').should('have.value', '100');

or try asserting using a promise

cy.get('propSizeSel').clear().type('100').invoke('val')
    .then(val=>{    
      const myVal = val;      
      expect(myVal).to.equal('100');
    })

With @soccerway answer and some changes I found a way to achieve what I want since I was unable to properly compare floats, indeed, if the field have for instance 1.320 and I want to check value is 1.32, with @soccerway answer using string I will have something like expected value to be '1.32' but got '1.320' error, I then have done:

    cy.get('propSizeSel')
      .invoke('val')
      .then(val => {
        if (val !== undefined) {
          expect(parseFloat(val.toString())).to.equal(1.32);
        } else {
          expect(val).not.equal(undefined);
        }
      });

In the case of this question parseInt can be used instead of parseFloat, and to go further, since I have several calls like this to do, I made a cypressCommonCommands.ts file that contains two function to do this:

export class CypressCommonCommands {
  public static expectElementValueEqualsFloat(pCyElement: string, pValue: number) {
    cy.get(pCyElement)
      .invoke('val')
      .then(val => {
        if (val !== undefined) {
          expect(parseFloat(val.toString())).to.equal(pValue);
        } else {
          expect(val).not.equal(undefined);
        }
      });
  }

  public static expectElementValueEqualsInt(pCyElement: string, pValue: number) {
    cy.get(pCyElement)
      .invoke('val')
      .then(val => {
        if (val !== undefined) {
          expect(parseInt(val.toString())).to.equal(pValue);
        } else {
          expect(val).not.equal(undefined);
        }
      });
  }
}

Then use for this question:

cy.get('propSizeSel').clear().type('100');
CypressCommonCommands.expectElementValueEqualsInt('propSizeSel', 100);
Related