Learn Cypress.io the hard way: Case-insensitive

During the web development process, sometimes values in HTML have inconsistent capitalization, which will lead to flaky tests. Sometimes, the tests will look for lower case text, but the actual text value will be in upper case. One of the common practices to improve such a flaky test is to make the text in case-insensitive way. In this post, I will you four different ways to make the text case insensitive.

The first approach is to use Cypress built-in feature to ignore case sensitivity. In this approach, the test will pass even if the text value in HTML is expected text instead of Expected Text. Cypress will ignore the upper case and only check the actual text content. You can turn on and off this feature by changing the value of matchCase from false to true.

cy.get('div').contains('Expected Text', { matchCase: false })

The second approach is to use Regex to ignore case sensitivity. In this approach, the i flag indicates that case should be ignored while attempting a match in a string.

cy.get('div').contains(/Expected Text/i)

The third approach is to change the string to lower case first before attempting a match. In this approach, the .toLowerCase(); function will convert all the alphabetic characters in a string to a lower case string.

    cy.get('div').should(($div) => {
      let text = $div.text().toLowerCase();
      let expectedText = 'Expected Text'.toLowerCase();
      expect(text).to.match(expectedText);
    });

The fourth approach is converting the characters in a string to lower case by using ASCII table. In the table below, you will see that #65 to #90 represent upper case A to Z , whereas #97 to #122 present lower case a to z. As such, if a character has a value between #65 to #90, we know this character is in upper case. By adding 32 to that character’s number, we can convert that character to lower case.

ASCII table

cy.get('div').should(($div) => {
  //  conver the characters to ASCII code
  let toLowerCaseCustomized = (str) => {
    // init an empty string
    let result = '';
    // Looping each char in the string
    for (let char of str) {
      // If the char ASCII code value is betwwen 65 to 90, we add 32 to it
      if (char.charCodeAt() <= 90 && char.charCodeAt() >= 65) {
        result += String.fromCharCode(char.charCodeAt() + 32);
      } else {
        // we keep the origin value
        result += char;
      }
    }
    // return the new string
    return result;
  };

  let text = $div.text();
  let expectedText = 'Expected Text';
  expect(toLowerCaseCustomized(text)).to.match(
    toLowerCaseCustomized(expectedText)
  );
});