如何使用cypress检查元素内部文本的相等性? [英] How do you check the equality of the inner text of a element using cypress?

查看:598
本文介绍了如何使用cypress检查元素内部文本的相等性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div,其中有另一个div,并且我想检查div内部文本的相等性。我已经知道如何使用invoke(‘text’)函数来做到这一点,但是我想知道这是否是最好的方法。所以我的问题是:如何使用cypress检查元素的内部文本是否相等?

I have a div that has another div inside of it and I want to check the equality of the inner text of the div. I have figured out how to do it using the invoke('text') function, but i am wondering if that is the best way. So my question is: how do you check the equality of the inner text of a element using cypress?

it('the channel name should contain be Anakin Skywaler', () => {
    //This works but can we be more specific with our selector
    cy.get("[data-test-id='Skywalker,Anakin']").should('contain', 'Skywalker,Anakin');
})

it('the channel name should equal Skywalker,Anakin', () => {

    cy.get("[data-test-id='Skywalker,Anakin']").find('.channel-name').invoke('text').then((text) => {
        expect(text.trim()).equal('Skywalker,Anakin')
    });
});    

请忽略《星球大战参考》!

Please ignore the Star War Reference!

推荐答案

我认为您可以简化此操作。

I think you can simplify this.

假设您有如下所示的HTML:

Assuming you have HTML that looks like this:

<div data-test-id="Skywalker,Anakin">
  <div class=".channel-name">Skywalker,Anakin</div>
</div>

您可以这样写断言:

cy.get('[data-test-id="Skywalker,Anakin"]')
      .should('have.text', 'Skywalker,Anakin');

这对我来说成功了,如果我将HTML修改为 Skywalker,Anakin 1 失败,正如您所料。赛普拉斯使用have.text来查看呈现的内容,因此它不必担心任何标记,而只看结果是什么。

This passed for me and if I modified the HTML to Skywalker,Anakin 1 it failed as you would expect. Cypress uses the have.text to look at what is rendered out so it will not worry about any markup and just see what the result is.

这不适用于修剪。您将需要添加回调以进行修整。

This did not work for trimming. you would need to add a callback to do the trimming.

cy.get('[data-test-id="Skywalker,Anakin"]')
  .should(($div) => {
    expect($div.text().trim()).equal('Skywalker,Anakin');
  });

这篇关于如何使用cypress检查元素内部文本的相等性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆