|
| 1 | +// TODO: Use aliased import(@cypress-dir) once #9631 is merged |
| 2 | +import { LABEL_CONFIG_KEYS } from './command_constants.js'; |
| 3 | + |
| 4 | +/** |
| 5 | + * Validates form field labels based on provided configurations |
| 6 | + * |
| 7 | + * @param {Array} labelConfigs - Array of label configuration objects |
| 8 | + * @param {string} labelConfigs[].forValue - The 'for' attribute value of the label |
| 9 | + * @param {string} [labelConfigs[].expectedText] - The expected text content of the label |
| 10 | + * |
| 11 | + * Example: |
| 12 | + * cy.validateFormLabels([ |
| 13 | + * { [LABEL_CONFIG_KEYS.FOR_VALUE]: 'name', [LABEL_CONFIG_KEYS.EXPECTED_TEXT]: 'Name' }, |
| 14 | + * { [LABEL_CONFIG_KEYS.FOR_VALUE]: 'email', [LABEL_CONFIG_KEYS.EXPECTED_TEXT]: 'Email Address' } |
| 15 | + * ]); |
| 16 | + * |
| 17 | + * Or using regular object keys: |
| 18 | + * cy.validateFormLabels([ |
| 19 | + * { forValue: 'name', expectedText: 'Name' }, |
| 20 | + * { forValue: 'email', expectedText: 'Email Address' } |
| 21 | + * ]); |
| 22 | + * |
| 23 | + * Both approaches work but using config-keys object(LABEL_CONFIG_KEYS) is recommended to avoid typos and unknown keys |
| 24 | + */ |
| 25 | +Cypress.Commands.add('validateFormLabels', (labelConfigs) => { |
| 26 | + if (!Array.isArray(labelConfigs)) { |
| 27 | + cy.logAndThrowError('labelConfigs must be an array'); |
| 28 | + } |
| 29 | + |
| 30 | + if (!labelConfigs.length) { |
| 31 | + cy.logAndThrowError('labelConfigs array cannot be empty'); |
| 32 | + } |
| 33 | + |
| 34 | + labelConfigs.forEach((config) => { |
| 35 | + const forValue = config[LABEL_CONFIG_KEYS.FOR_VALUE]; |
| 36 | + const expectedText = config[LABEL_CONFIG_KEYS.EXPECTED_TEXT]; |
| 37 | + |
| 38 | + if (!forValue) { |
| 39 | + cy.logAndThrowError( |
| 40 | + `${LABEL_CONFIG_KEYS.FOR_VALUE} is required for each label config` |
| 41 | + ); |
| 42 | + } |
| 43 | + |
| 44 | + const labelCheck = cy |
| 45 | + .getFormLabelByForAttribute({ forValue }) |
| 46 | + .should('be.visible'); |
| 47 | + |
| 48 | + if (expectedText) { |
| 49 | + labelCheck.and('contain.text', expectedText); |
| 50 | + } |
| 51 | + }); |
| 52 | +}); |
0 commit comments