Text Validations in Cypress

CypressTest AutomationSoftware Testing

Cypress can validate the text on an element with the help of jQuery text() method. This method shall help us to fetch the text content on the selected element. We can also put assertions on the text content of the element.

cy.get('.product').should('have.text', 'Tutorialspoint');

We can do validations on the text like verify what it contains or matches with the help of the Javascript methods match(), include() and so on. Thus Cypress commands can work on non-Cypress methods with the help of jQuery objects and invoke methods on them.

Example

Code Implementation with the text() method.

// test suite
describe('Tutorialspoint Test', function () {
// test case
it('Test Case1', function (){
// test step to launch a URL
cy.visit("https://www.tutorialspoint.com/index.htm");
// enter test in the edit box
// assertion to validate the number of child elements
cy.get('#gs_50d > tbody > tr > td'). should('have.length',2);
// locate element with get and find method
cy.get('#gs_50d > tbody > tr > td'). find('input')
//enter test in the edit box
.type('Cypress');
//iterate the list items with each command
cy.get('.mui-tabs__bar.mui-tabs__bar_1.mui-tabs__bar--justified)
.find('li').each(($el, index, $list) => {
// extract text with text() method
const txt = $el.find('a').text();
if ( txt.includes('Deve')){
$el.click();
}
})
});
});

On running the above block of code, Cypress Test runner gives the below output −

raja
Published on 05-Aug-2020 11:57:03
Advertisements