I have a project that doesn't capitalize on level of HTML and values in HTML have inconsistent capitalization.
Is there any way how to force Cypress to match text if I use only lower-case strings as arguments to contains() function?
Cypress contains methods already have such feature. You can just pass the matchCase
as options argument and cypress will handle case sensistive/insensitive conditions. Below code snippet will help you.
If you like the answer, please like the answer and give vote up.
it('this will pass', () => {
cy.visit('https://example.cypress.io');
cy.contains('commands drive your tests', {matchCase: false})
});
it('this will fail', () => {
cy.visit('https://example.cypress.io');
cy.contains('commands drive your tests', {matchCase: true})
})
contains()
can take a regular expression, for which you can specify case-insensitive matching with the i
flag:
Other answers already mention this, but this might be the easiest way to use it:
cy.get('.some-selector').contains(/match cAse-InSENsitiVE/i);
You can add a case-insensitive regex to the contains command, although using regex you need to be careful to escape any special regex characters,
see this Escape string for use in Javascript regex
const escapeRegExp = (string) => {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
const expected = 'mYtEXTtO*tEST?';
const regex = new RegExp(escapeRegExp(expected), 'i');
cy.contains(regex);
cy.contains('MySelector', regex);
You could use a regex.
cy.get("#whatever").its("something").should("match", "[your regex here]")
Cypress has lodash included. So, this is my current workaround for non case sensitive text matching, until Cypress includes this feature for cy.contains()
cy.get('p.heading').then( $headings => {
let texts = $headings.map( (_, el) => (Cypress._.toUpper(el.textContent)));
expect(texts.get()).to.include('INCONSISTENT CAPITALIZED TITLE 1');
//If you have more to match
expect(texts.get()).to.include('INCONSISTENT CAPITALIZED TITLE 2');
});
For Cypress 10 you can use this override to make contain not match case by default
// set match case to default false
Cypress.Commands.overwrite('contains', (originalFn, subject, value, options) => {
const matchCase = options?.matchCase || false;
return originalFn(subject, value, { ...options, matchCase });
});