skip to Main Content

I’m trying to assert the value of an input field:

cy.get('[data-vv-name="item price"]')
    .then(response => {
        expect(response.value).to.be.equal('100')
    })

But I’m getting an error:

Property 'value' does not exist on type 'JQuery<HTMLElement>'

But when I try the code to the console:

$('[data-vv-name="item price"]').value

I’m able to get the correct value of ‘100’.
What should I add/update to make my assertion correct? Am I missing anything here?

EDIT:

Using the following, I was able to do my assertion

expect((<HTMLInputElement>response[0]).value).to.be.equal(10)

2

Answers


  1. An HTMLElement could be an <input> which has a value, but it could be a <div> which does not.

    You need to narrow the type. You can do that by testing for the existence of the value property:

    .then(response => {
        if ('value' in response) 
            expect(response.value).to.be.equal('100');
        else
            throw new Error("Expected an HTML element with a value property but did not get one");
    })
    
    Login or Signup to reply.
  2. jQuery objects don’t have .value property, but they do have .val() method that you could use

    cy.get('[data-vv-name="item price"]')
      .then($el => {
        // $el is convention for naming jQuery objects
        expect($el.val()).to.be.equal('100')
      })
    

    or use .invoke() in the chain (ref invoke)

    cy.get('[data-vv-name="item price"]')
      .invoke('val')
      .then(value => {
        expect(value).to.be.equal('100')
      })
      .should('eq', '100')    // alternative to above assertion
    

    or you can use the .should('have.value', ...) chainer (ref should)

    cy.get('[data-vv-name="item price"]')
      .should('have.value', '100')
    

    or use the .value property of the unwrapped element as you have shown

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search