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.
As you can see the input element has accepted the value 100 as expected:
Why is it that I can't seem to make this simple assertion?
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');
})
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With