简体   繁体   中英

Cypress - How to return the new value from .then()?

So, I am using Cypress and I want to change the value from the variable. Look at my script below:

let bankBranch = Base Data;
 
cy.get("#bankBranch").then(() => {
  bankBranch = bankBranch.replace(/\s+/g, '+');
}).type(bankBranch);

I want Cypress to type it as "Base+Data". But, it still typing "Base Data".

How to do it?

Thank you.

I guess you have to understand that Cypress commands run asynchronously from the javascript in the test.

Move the .type() inside the .then() so it happens after you modify the value

let bankBranch = 'Base Data';

cy.get("#bankBranch").then($el => {
  bankBranch = bankBranch.replace(/\s+/g, '+');
  cy.wrap($el).type(bankBranch)
})

There are other refactors, I recommend playing around.

// replace the space early
let bankBranch = 'Base Data'.replace(/\s+/g, '+')

cy.get("#bankBranch")
  .type(bankBranch)
let bankBranch = 'Base Data';

cy.get("#bankBranch").then($el => {
  bankBranch = bankBranch.replace(/\s+/g, '+');
  // pass on the element
  return $el
}).then($el => {
  // deferring the .type() command
  cy.wrap($el).type(bankBranch)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM