简体   繁体   English

如何使用 JS 或 TS 在 Cypress 中从.then 返回文本值

[英]How to return text value from .then in Cypress using JS or TS

I need to access data outside from then.从那时起我需要访问外部数据。

   function getText() {
    cy.get('#locator')
        .then(function($elem) {
            let aaa = cy.log($elem.text());
            return aaa.toString();
        });
   }

   var returnedValue = getText();
   cy.log(returnedValue);

I get the error: Argument of type 'void' is not assignable to parameter of type 'string' , when I try to print the output in the Cypress test runner log.我收到错误:当我尝试在 Cypress 测试运行器日志中打印 output 时, Argument of type 'void' is not assignable to parameter of type 'string' 在此处输入图像描述

  1. Your getText() does not return anything, hence the argument of type void... error.您的getText()不返回任何内容,因此argument of type void...
  2. You're trying to convert a cy.log() command into a string, which is not feasible.您正在尝试将cy.log()命令转换为字符串,这是不可行的。

Instead, let's yield the result of your getText() command into a .then() that uses cy.log() ;相反,让我们将getText()命令的结果生成到使用cy.log() .then()

const getText = () => {
  return cy // return the entire chain
    .get('#locator')
    .then(($elem) => {
       return $elem.text(); // return the text of the element
    });
}

getText().then((result) => {
  cy.log(result);
});

If you need to do something besides cy.log() that value, just do the same, and use that result variable.如果您需要在cy.log()那个值之外做一些事情,只需做同样的事情,并使用那个result变量。

getText().then((result) => {
  // code that uses result
});

I would not advise declaring a variable and setting it equal to getText() , because that is going to assign the variable a value of type Chainable<string> , and not string , which is not what you want or need.我不建议声明一个变量并将其设置为等于getText() ,因为这将为变量分配一个Chainable<string>类型的值,而不是string ,这不是您想要或需要的。

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

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