Home > database >  How do I get the input value of a MUI TextField with cypress?
How do I get the input value of a MUI TextField with cypress?

Time:11-25

I am using cypress to test that a textfield displays the entered text correctly.

cy.get('.creation-name').should('not.have.text');
const testName = 'Test name';
cy.get('.creation-name').type(`${testName}`);

TextField is a MUI component and this is a React project.

<div className="create-name">
    <TextField
        id="Name"
        label="Create name"
        onChange={(event) => setName(event.target.value)}
    />
</div>

I can see from the video that the text types in fine, but when I try to check that it's there it fails. I have tried multiple different lines to get the test text value, including these:

//got AssertionError for all of these
cy.get('.creation-name').invoke('val').should('equal', 'Test name');//expected '' to equal Test name
cy.contains(`${testName}`).should('have.text', `${testName}`);//expected '' to equal Test name
cy.get('[id="Name"]').should('have.text', `${testName}`);//expected '' to equal Test name
cy.get('.creation-name').invoke('text').should('equal', 'Test');//expected Create name to equal Test name
cy.get('.creation-name').should('have.text', `${testName}`);//expected Create name to equal Test name

Seems I am not getting anything or I am targeting the label. This is my first time using cypress so I hope I didn't miss anything obvious.

CodePudding user response:

Try taking the value from the child <input>.

cy.get('.creation-name')  // or .create-name, maybe a typo in the question
  .find('input')
  .invoke('val')
  .should('equal', 'Test name')

The contains() and text related commands won't work because it's an input, which hold the value internally.

Text commands only work for element that have the text between tags like <div>Test text</div>.

CodePudding user response:

Have you tried this ?

cy.get('input[id="Name"]').invoke('val').then(value => assert.equal(value, testName));
  • Related