Skip to main content

Cypress Text Verification

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

Video Tutorial: Verify Text in Cypress

Tags
Submitted by arilio666 on June 7, 2022

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.