javascript 如何使用 jquery 在 Cypress 测试中获取 div 'text' 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52491253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get div 'text' value in Cypress test using jquery
提问by soccerway
Using Jquery in Cypress.io test, how to get the div 'text' value called 'Wildness' from the below html tag. I have tried below in my Cypress test, but it is throwing undefined in console.
在 Cypress.io 测试中使用 Jquery,如何从下面的 html 标签中获取名为 'Wildness' 的 div 'text' 值。我在我的 Cypress 测试中尝试过下面的尝试,但它在控制台中抛出 undefined 。
const $divText = Cypress.$('.ibxudA .WildnessText-kRKTej').text()
cy.wrap($divText)
.should("eq", "Wildness")
<div class="sc-bMvGRv_onetwo">
<div>
<div class="abLeftSection">
<div class="abNewBtn-fTLJBK">
<button class="ifAKCX ohpWT" type="button">New</button>
</div>
<div class="kpLvEV" style="">
<div class="cWzXYZ">
<div class="OgGUG">
<div class="jsnnAD">
<svg class="dFvKsA"></svg>
</div>
</div>
<div class="ibxudA">First</div>
</div>
<div class="kpLvEV" style="">
<div class="bGADLM"><div class="OgGUG">
<div class="jsnnAD">
<svg class="dFvKsA"></svg>
</div>
</div>
<div class="ibxudA">
<div class="WildnessText-kRKTej" title="Wildness">Wildness</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
回答by Maccurt
I might try this:
我可以试试这个:
cy.get(".ibxudA").find('.WildnessText-kRKTej').invoke('text').then((text) => {
expect(text.trim()).equal('Wildness')
});
or
或者
cy.get(".ibxudA").find('.WildnessText-kRKTej').should('have.text',"Wildness")
This might be a similar question: How do you check the equality of the inner text of a element using cypress?
这可能是一个类似的问题:如何使用 cypress 检查元素内部文本的相等性?
回答by Singhak
cy.get("WildnessText-kRKTej").then(function($elem) {
cy.log($elem.text())
})
回答by yogesh dhiman
I would suggest you use inbuilt cypress API 'contains' like this:
我建议您使用内置的 cypress API 'contains',如下所示:
cy.contains('Wildness')
It will select the whole HTML tag for you. Hope it helps...
它将为您选择整个 HTML 标签。希望能帮助到你...
回答by Sourabh
One line validation:
一行验证:
Syntax:
句法:
cy.get(<selector>).invoke("text").should("eq", <your string>);
Example:
例子:
cy.get("div.myclass").invoke("text").should("eq", "My Text");
Here, following method is used for retrieving text. should()is used for validation.
在这里,以下方法用于检索文本。should()用于验证。
cy.get('element').invoke('text')
回答by R. M.
it('get text', async () => {
const text = await new Cypress.Promise<string>((resolve) => {
cy.get('[data-testid="target"')
.invoke('text')
.then((txt) => resolve(txt.toString()))
})
cy.log(text)
})
回答by Cleriston
cy.get('.ibxudA .WildnessText-kRKTej').invoke('text').then((yourDivText) => {
expect(yourDivText.toString().toLowerCase()).to.contain('wildness');
});

