Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asserting that an input element contains a specific value in Cypress

Tags:

cypress

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?

like image 321
p4t Avatar asked Dec 11 '22 04:12

p4t


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');
    })
like image 118
soccerway Avatar answered Dec 31 '22 14:12

soccerway


As for 2022 there is a variety of approaches Cypress offers to assert a number input value, an entire string match, a substring, a regex or make a more complex custom assertions. Here is how.

// Assume we have an input with `.my-input-class` class and the value `My input value` 
// in the markup.

// Then we find it (NB: do not forget getting the single one here e.g. with `.first()`
// as there can be many of the selected elements returned by `cy.get()`)
cy.get('.my-input-class).first()
    // This gets the input value for further assertions
    .invoke('val')
    // This would succeed if we had a number input with value `100`
    .should('have.value', 100)
    // Again for number
    .should('be.equal', 100)
    // And again, now with "greater then or equal" assertion
    .should('be.at.least', 100)
    // Now for strings, this matches the entire string
    .should('contain', 'My input value')
    // This matches the substring
    .should('include', 'My input')
    // Another substring match
    .should('have.string', 'My input')
    // Regex is here
    .should('match', /My/)
    // Here you can make any complex custom assertions JavaScript allows
    .then(($valueString)=>{
        console.log($valueString)
        if (!$valueString.includes('My')) {
            throw new Error('My custom assertion fails the test')
        }
    })

There are many string assertions you can make via Cypress, within should family or beyond. See the official docs.

like image 31
Valentine Shi Avatar answered Dec 31 '22 15:12

Valentine Shi