好的,我想从div和一个类中获取文本。 html看起来像这样:
<div class="inventory_item_name">Backpack</div>
我的代码是这样:
const article = cy.get('.inventory_item_price').then((theElement) => {
theElement.text();
});
问题:cy.log(article)
出现后Object{5}
答案 0 :(得分:1)
就像注释中提到的Alex一样,您无法从cy
命令返回值。但是您可以在.then
块中这样做,就像:
it("should have text of 'Backpack'", () => {
// I have changed the selector since the class name in your HTML is ".inventory_item_name" not ".inventory_item_price"
cy.get(".inventory_item_name").then(($el) => {
const text = $el.text(); // Now you have the text "Backpack"
// Do the assertion here
expect(text).to.eq("Backpack");
});
});
您可以在此documentation
中了解有关赛普拉斯为什么不返回值的更多信息。答案 1 :(得分:0)
如赛普拉斯文档所述
您不能分配或使用任何返回值 赛普拉斯命令。命令已排队并异步运行。
// this won't work the way you think it does
const button = cy.get('button')
const form = cy.get('form')
button.click()
有关更多信息,请参见:variables-and-aliases
您有一些选择。但是您需要牢记柏树的异步特性
示例:
it("Test 1", () => {
cy.get('.inventory_item_price').invoke('text').as('article')
})
//Now you can use this.article in all the other test cases
//If you are using aliases remember Not to use arrow functions on hooks
it("Test 2", function(){
//this will log Backpack
cy.log(this.article)
})
.then
,正如@konekoya在答案中提到的那样,由于cypress是异步的,因此您需要在上一个任务完成后使用.then
来执行任务。示例:
cy.get('.inventory_item_price').invoke('text').then(article=> {
//you can use articale variable as much as you want inside .then
//you can't use it outside
const value = articale ;
cy.log(article)
cy.log(value )
})
注意:要获取内部Text,您有几种方法。您可以使用
cy.get('.inventory_item_price').then(article => {
const value = articale.text() ;
cy.log(article.text())
cy.log(value)
})
答案 2 :(得分:0)
您不能分配这样的文本值。
filter(ev : any)
原因是下面的代码没有返回文本元素。
filter(ev : any) {
// Filtering code
const val = ev.target.value;
if(val && val.trim() !== ''){
this.recipeData = this.recipeData.filter((item) => {
return(item.Name.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
}
}
所以您需要像这样更改它。
const article = cy.get('.inventory_item_price').then((theElement) => {
theElement.text();
});
答案 3 :(得分:-1)
您可以使用以下代码返回文章文本。另外,请查看我分享答案的链接。
Storing an element's text in Cypress outside of a chainer method
return cy.get('.inventory_item_price').then((theElement) => {
return theElement.text();
}).then(article => {
cy.log(`article is ${article}`);
})