Typing a variable in cypress and then pressing enter

Viewed 421

I am trying to pass a variable to a cypress function to type and then press enter.

I have found that this doesn't work.

const valToType = "ABCD"
cy.get('#MyID').type(valToType).type('{enter}');

I have seen elsewhere the workaround is to do

cy.get('#MyID').type('ABCD{enter}');

However I'd really like to keep this a variable. Anyone know how this is possible with cypress?

2 Answers

You should be able to use string interpolation to pass your variable and press the enter key in a single type() command, like this:

cy.get('#MyID').type(`${valToType}{enter}`);

You have to wrap your variable like this:

const valToType = "ABCD"
cy.wrap(valToType).then((val) => {
    cy.get('#MyID').type(val).type('{enter}');
})
Related