Cypress Text Verification

Profile picture for user arilio666

Since Cypress comes bundled with different tools and libraries, it gives you flexibility in writing code. To verify or validate text on the web page, you can use multiple techniques, a few of which we will discuss in this article.

Before you proceed, note the following points:

  • Following Keywords  (.to, .be, .been, .is, .that, .and, .have, .with, .at .of, .same) in your assertions does not do anything, these are used in BDD Style to make your code meaningful.
  • equals, equal, or eq are aliases
  • contain, include, and contains are aliases, but for contains object tested must be an array, a map, an object, a set, a string, or a weakset 

Example

Demo Link: https://www.programsbuzz.com/course/cypress-tutorial

cypress should have text

We will verify Cypress Tutorial heading on above link with selector h1.page-title>span

Cypress Should Have Text 

// exact match
cy.get('h1.page-title>span').should('have.text', 'Cypress Tutorial')

//Partial Match
cy.get('h1.page-title>span').should('include.text', 'Cypress Tutor')
cy.get('h1.page-title>span').should('contain', 'Cypress Tutor')

Invoke Cypress Text

cy.get('h1.page-title>span')
    .invoke('text')
    .then((t) => {
        // exact match
        expect(t).equal('Cypress Tutorial')
        expect(t).equals('Cypress Tutorial')
        expect(t).eq('Cypress Tutorial')

        //partial match
        expect(t).include('Cypress Tutor')
        expect(t).contain('Cypress Tutor')
        expect(t).contains('Cypress Tutor')
})

Using Text Function

cy.get('h1.page-title>span').then(($e) => {
    const t = $e.text()

    // exact match
    expect(t).equal('Cypress Tutorial')
    expect(t).equals('Cypress Tutorial')
    expect(t).eq('Cypress Tutorial')

    //partial match
    expect(t).contain('Cypress Tutor')
    expect(t).contains('Cypress Tutor')
    expect(t).include('Cypress Tutor')
})