Closed rogoit closed 1 year ago
describe('Test Kontrastverhältnis', () => { it('prüft Kontrastverhältnis zwischen Text und Hintergrundfarbe', () => { cy.get('body') .should('have.css', 'background-color') .then(bgColor => { cy.get('body').find('p, h1, h2, h3, h4, h5, h6, span, a') .each(el => { cy.wrap(el).should($el => { const textColor = $el.css('color'); const contrastRatio = getContrastRatio(textColor, bgColor); expect(contrastRatio).to.be.greaterThan(4.5); }); }); }); }); });
function getContrastRatio(color1, color2) { const l1 = getLuminance(color1); const l2 = getLuminance(color2); return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05); }
function getLuminance(color) { const rgb = parseColor(color); const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const lum = 0.2126 r + 0.7152 g + 0.0722 * b; return lum; }
function parseColor(color) { if (color.substr(0, 1) === '#') { return [ parseInt(color.substr(1, 2), 16), parseInt(color.substr(3, 2), 16), parseInt(color.substr(5, 2), 16), ]; } else if (color.substr(0, 3) === 'rgb') { const values = color.substring(color.indexOf('(') + 1, color.lastIndexOf(')')).split(','); return [parseInt(values[0]), parseInt(values[1]), parseInt(values[2])]; } }
it('Color contrast', () => { cy.visit('/path'); cy.get('body').then(($body) => { const bgColor = $body.css('background-color'); cy.get('h1, h2, p, a, button').each(($el) => { const color = $el.css('color'); const contrast = Cypress.ColorUtil.contrast(color, bgColor); expect(contrast).to.be.greaterThan(4.5); }); }); });