Cypress test validation

Viewed 348

I have function to convert text to Uppercase, what i want to do is to write test in cypress for the fonction and print the result in htmml

here the function :

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

here i print it :

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

so how i should write the test :

i know i could do this :

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

but i want somthing like this : example:

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

is it possible?

2 Answers

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

You can use regex as well to check that the text has uppercase or not.

cy.get('[cy-data=uppercase]')
  .invoke('text')
  .should('match', /\b[A-Z]+\b/)

To check if everything in the sentence is in uppercase along with special characters you can use the regex ^[^a-z]*$

cy.get('[cy-data=uppercase]')
  .invoke('text')
  .should('match', /^[^a-z]*$/)

You can play around with regex as per your requirement.

Related