Cypress – Text Verification

The method text can be used to obtain the text of a web element. Assertions can also be added to verify the text content.

Implementation with text()

Given below is the command for the implementation with text() with regards to verification −

// test suite
describe('Adglob', function () {
   // it function to identify test
   it('Scenario 1', function (){
      // test step to launch a URL
      cy.visit("https://accounts.google.com")
      // identify element
      cy.get('h1#headingText').find('span').then(function(e){
         //method text to obtain text content
         const t = e.text()
         expect(t).to.contains('Sign')
      })
   })
})

Execution Results

The output is as follows −

The output logs show the text Sign in obtained with the text method.

Implementation with text assertions

We can also implement assertions on web element text with the help of the following command −

// test suite
describe('Adglob', function () {
   // it function to identify test
   it('Scenario 1', function (){
      // test step to launch a URL
      cy.visit("https://accounts.google.com")
      // verify text with have.text
      cy.get('h1#headingText').find('span').should('have.text','Sign in')
   })
})

Execution Results

The output is mentioned below −

The output logs show the text verification done with should assertion.

Leave a Reply