Search code examples
validationcypresschai

Cypress test validation for uppercase


I have function to convert text to uppercase, what I want to do is to write test in cypress for the function and print the result in HTML

Here the function :

module.exports = () => ({
  upperCaseName: (name) => {
    return name.toUpperCase()
  }
});

Here I print it :

<h1 cy-data='uppercase'> the result </h1>

How I should write the test? I know I could do this:

cy.get('[cy-data=uppercase]').contains('the result')

but I want something like this:

cy.get('[cy-data=uppercase]').to.be.upperCase

Solution

  • How about

    cy.get('[cy-data=uppercase]').contains('THE RESULT', { matchCase: true })
    

    but { matchCase: true } is the default setting, so can be just

    cy.get('[cy-data=uppercase]').contains('THE RESULT')
    

    Custom Chai assertion for uppercase

    
    window.chai.Assertion.addProperty('uppercase', function () {
      var obj = this._obj;
      new chai.Assertion(obj).to.be.a('string');
    
      this.assert(
          obj === obj.toUpperCase()
        , 'expected #{this} to be all uppercase'    // error message when fail for normal
        , 'expected #{this} to not be all uppercase'  // error message when fail for negated
      );
    });
    
    it('test for upper case (and not uppercase)', () => {
    
      cy.get('[cy-data=uppercase]').invoke('text').should('be.uppercase')
      cy.get('[cy-data=lowercase]').invoke('text').should('not.be.uppercase')
      
    })
    

    Extends internal Cypress version of Chai with new assertion, works in .should() with retry and timeout as well.


    Or without custom chai assertion

    it('test for upper case (and not uppercase)', () => {
    
      cy.get('[cy-data=uppercase]').invoke('text')
        .should(text => expect(text).to.eq(text.toUpperCase())
    
      cy.get('[cy-data=lowercase]').invoke('text')
        .should(text => expect(text).not.to.eq(text.toUpperCase())
      
    })