Soy nuevo en Cypress y trato de escribir una afirmación para algunas entradas de texto para un nombre de usuario. Un texto válido para un nombre de usuario debe cumplir dos condiciones, que son,
Mi código es el siguiente.
getUserFirstName(textInput) { cy.get('[testid="user-self-update-form"]') .get('input[name="firstName"]') .clear() .type(textInput) .blur() .invoke('val') .should(($el) => { expect($el).to .match(/[a-zA-Z]+$/) .to .have .greaterThan(1) .to .be .lessThan(20) }).then(() => { cy.log("Invalid text input"); }) }Mi requisito : cuando se inserta un texto de nombre de usuario, la prueba anterior debe verificar si cumple con las condiciones impuestas; de lo contrario, registrar un mensaje en la consola. Ahora estoy tratando de hacer la prueba anterior para 4 entradas por separado, que son 'abcd123', '123', 'textwithmorethantwentyletters' y 'belowtwenty'. Al ejecutar esta prueba para el primer texto de entrada de 'abcd123'. ¿Cómo puedo corregir este código? Agradezco mucho su ayuda.
Recibo el siguiente error y la prueba falla:
Para obtener un registro elegante de las condiciones, use Cypress.log
getUserFirstName(textInput) { cy.get('[testid="user-self-update-form"]') .find('input[name="firstName"]') .clear().type(textInput).blur() .invoke('val') .then(val => { // Conditions const lettersOnly = val.match(/[a-zA-Z]+$/) const correctLength = val.length > 1 && val.length < 20 Cypress.log({ name: 'firstNameCheck', displayName: `Testing "${textInput}"`, message: ` - lettersOnly: ${lettersOnly ? 'pass' : 'fail'}` }) Cypress.log({ name: 'firstNameCheck', displayName: `Testing "${textInput}"`, message: ` - correctLength : ${correctLength ? 'pass' : 'fail'}` }) // now fail if you want, or omit this to perform next textInput expect( lettersOnly && correctLength ).to.eq(true) }) } const textInputs = ['abcd123', '123', 'textwithmorethantwentyletters', 'belowtwenty'] textInputs.forEach(textInput => getUserFirstName(textInput)) También puede suprimir el registro de find , type , invoke con la opción {log:false} .
Puedes intentar encadenar las condiciones con Cypress .and()
getUserFirstName(textInput) { cy.get('[testid="user-self-update-form"]') .find('input[name="firstName"]') .clear() .type(textInput).blur() .invoke('val') .should('match', /[a-zA-Z]+$/) .and('have.length.gt', 1) .and('have.length.lt', 20) } La entrada abc123 no cumple con el primer criterio, ¿por qué pensó que pasaría la prueba?
Si solo desea iniciar sesión pero no fallar la prueba, intente
getUserFirstName(textInput) { cy.get('[testid="user-self-update-form"]') .find('input[name="firstName"]') .clear() .type(textInput).blur() .invoke('val') .then(val => { const lettersOnly = val.match(/[a-zA-Z]+$/) const gt1 = val.length > 1 const lt20 = val.length < 20 if (!lettersOnly || !gt1 || !lt20) { cy.log('Failed conditions') // to fail the test now, throw an error throw 'Failed conditions' }) }) } En el segundo ejemplo, no .should() , .and( .and() o expect() porque si alguno de ellos falla, Cypress fallará la prueba en ese punto (y no verificará las otras condiciones).
Tenga en cuenta también, .find(('input[name="firstName"]') en lugar de .get('input[name="firstName"]') porque su intención es encontrar la entrada del nombre dentro del formulario.
.get() también puede funcionar si solo hay una 'input[name="firstName"]' en la página, pero tenga en cuenta que ignora la línea anterior y consulta DOM desde el elemento raíz <body> .
Su respuesta es mayormente correcta, pero solo necesita algunos cambios.
expect($el).to.match(/[a-zA-Z]+$/) expect($el.length).to.have.greaterThan(1).to.be.lessThan(20)También puede usar dentro de la cual básicamente verifica mayor y menor que.
expect($el.length).to.be.within(1,20)cy.log("Invalid text input"); puede pasar directamente mensajes de registro personalizados en declaraciones de expectativa. expect($el.length).to.be.within(1,20, "Some Log message")Entonces, al implementar estos dos cambios, su código debería verse así:
cy.get('[testid="user-self-update-form"]') .get('input[name="firstName"]') .clear() .type(textInput) .blur() .invoke('val') .should((val) => { expect(val.trim()).to.match(/[a-zA-Z]+$/, `Checking username ${val} for regex match` ) expect(val.trim().length).to.be.within(1,20, `Checking username ${val} for length match` ) })