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.
Assuming you have HTML that looks like this:
You can write your assert like this:
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.
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.
You can check if a string is contained somewhere inside the div:
Or, if you need to make sure the div contains only the specified text and nothing else, you can tag on this extra assertion:
Explanation:
Following is how you can check exact or partial match for a string in an element:
where
text()
is defined incommand.js
file as following: