[英]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' 。
getText()
does not return anything, hence the argument of type void...
error.getText()
不返回任何内容,因此argument of type void...
。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.