How do you check the equality of the inner text of a element using cypress?

I think you can simplify this.

Assuming you have HTML that looks like this:

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

You can write your assert like this:

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

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");
});

I think currently this is the best option, because it does not check for contains. I was hoping for a shorter piece of code to do this.

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')
    });
});

Following is how you can check exact or partial match for a string in an element:

//matches exact text of result string
cy.get("[data-test-id='Skywalker,Anakin']").should('have.text', 'Skywalker,Anakin');

//matches partial text of result string
cy.get("[data-test-id='Skywalker,Anakin']")
.text()
.then(value => {
        cy.log("Text value is :", value);
        expect(value).to.include('Anakin');
});

where text() is defined in command.js file as following:

Cypress.Commands.add("text", { prevSubject: true }, (subject, options) => {
  return subject.text();
});

You can check if a string is contained somewhere inside the div:

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

Or, if you need to make sure the div contains only the specified text and nothing else, you can tag on this extra assertion:

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

Explanation:

// Get the data
cy.get("[data-test-id='Skywalker,Anakin']")

        // Get the child or children of the previous command that
        // contain the text - this command fails if no child
        // element is found containing the given text
        .contains('Skywalker,Anakin');
// These two lines are explained above
cy.get("[data-test-id='Skywalker,Anakin']")
        .contains('Skywalker,Anakin')

        // Like a .then(), except the contents are retried until
        // all contained assertions are successful or until the
        // command times out
        .should((elem) => {

            // Expect the element's text to exactly equal the
            // string, not just contain it
            expect(elem.text()).to.equal('Skywalker,Anakin');
        });

Tags:

Cypress