简体   繁体   English

Cypress - 如何从.then() 返回新值?

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

So, I am using Cypress and I want to change the value from the variable.所以,我正在使用 Cypress,我想更改变量的值。 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".我希望 Cypress 将其键入为“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.我猜你必须明白 Cypress 命令从测试中的 javascript 异步运行。

Move the .type() inside the .then() so it happens after you modify the value.type() .then()中,以便在您修改值后发生

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)
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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