Gabriel Jiménez | Hace alrededor de 1 año
Para este post, vamos a implementar las dos ultimas pruebas.
Iniciemos definiendo el nombre de nuestra prueba.
72: it('si se selecciona teléfono no enviar el correo electrónico', () => { 73: 74: });
El flujo de la prueba es el siguiente:
Veamos la implementación.
src/CreateTwitchAccount.test.js … 72: it('si se selecciona teléfono no enviar el correo electrónico', async () => { 73: wrapper() 74: 75: await CreateTwitchAccountPageObject.fillUpUsername('Gabriel') 76: CreateTwitchAccountPageObject.fillUpPassword('Hola1234#') 77: CreateTwitchAccountPageObject.fillUpBirthdate('10-01-1990') 78: CreateTwitchAccountPageObject.fillPhone("5512039482") 79: 80: CreateTwitchAccountPageObject.submit() 81: 82: expect(props.createAccount).toHaveBeenCalledWith(expect.not.objectContaining({ 83: email: undefined 84: })) 85: expect(props.createAccount).toHaveBeenCalledWith(expect.objectContaining({ 86: phone: '5512039482' 87: })) 88: });
Analicemos.
Línea 75..78. Llenamos el campo nombre de usuario, contraseña, fecha de nacimiento y teléfono
Línea 80. Enviamos el formulario
Línea 82..84. Validamos que el createAccount no contiene el campo email
Línea 85..87. Validamos que el createAccount viene el campo phone
Agregamos una función para llenar campo teléfono en nuestro PageObject.
src/CreateTwitchAccountPageObject.js … 33: static fillPhone(value) { 34: fireEvent.change(screen.getByTestId('phone'), { target: { value } }) 35: }
src/CreateTwitchAccount.js … 66: <input type="text" name="phone" 67: data-testid="phone" placeholder="Télefono" onChange={onChange}/> … 69: </form>
src/CreateTwitchAccount.js … 6: const [showEmail, setShowEmail] = useState(false) … 13: function validateValuesPreSubmit() { 14: const { email, password } = values 15: 16: const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ 17: if(email && !emailRegex.test(email)) { 18: throw new Error("El correo electrónico tiene un formato incorrecto") 19: } … 54: return( 55: <form onSubmit={handleSubmit}> … 81: { 82: showEmail ? 83: <input type="text" name="email" 84: data-testid="email" placeholder="Correo electrónico" onChange={onChange}/> : 85: <input type="text" name="phone" 86: data-testid="phone" placeholder="Télefono" onChange={onChange}/> 87: } …
Analicemos
Línea 6. Creamos un estado para mostrar y ocultar el campo email.
Línea 17. Solo si el campo email esta definido realiza la validación del formato del email
Línea 81..87. Creamos un estado para ocultar y mostrar el campo email, por defecto es false. Cuando ocultamos email, mostramos teléfono y viceversa.
Veamos la solución.
src/CreateTwitchAccount.test.js … 20: it('crear cuenta correctamente', async () => { … 23: await CreateTwitchAccountPageObject.fillUpUsername('Gabriel') 24: CreateTwitchAccountPageObject.fillUpPassword('Hola1234#') 25: CreateTwitchAccountPageObject.fillUpBirthdate('10-01-1990') 26: CreateTwitchAccountPageObject.showEmailField() 27: CreateTwitchAccountPageObject.fillUpEmail('[email protected]') … 50: 51: it('si el formato del correo electrónico es incorrecto, mostrar mensaje de error ', async () => { … 53: 54: CreateTwitchAccountPageObject.showEmailField() 55: await CreateTwitchAccountPageObject.fillUpForm() 56: CreateTwitchAccountPageObject.fillUpEmail('hola@correosinformatovalido') 57: 58: CreateTwitchAccountPageObject.submit() 59: … 62: 63: it('si el formato de la contraseña es incorrecto, mostrar mensaje de error', async () => { … 65: 66: CreateTwitchAccountPageObject.showEmailField() 67: await CreateTwitchAccountPageObject.fillUpForm() 68: CreateTwitchAccountPageObject.fillUpPassword('hola1234') 69: 70: CreateTwitchAccountPageObject.submit() …
Analicemos
Línea 26. Muestra el campo email para poder llenarlo en la línea 27
Línea 54. Muestra el campo email para poder llenarlo en la línea 55
Línea 66. Muestra el campo email para poder llenarlo en la línea 67
Por último, ataquemos la última prueba.
src/CreateTwitchAccount.test.js … 93: it('deshabilitar el botón de "Registrar" cuando los campos obligatorios no se hayan llenado', async () => { 94: wrapper() 95: 96: await CreateTwitchAccountPageObject.fillUpUsername('Gabriel') 97: CreateTwitchAccountPageObject.fillUpPassword('Hola1234#') 98: CreateTwitchAccountPageObject.fillPhone("5512039482") 99: 100: CreateTwitchAccountPageObject.submit() 101: 102: expect(screen.getByText("Guardar").disabled).toBeTruthy() 103: }); …
Analicemos
Línea 96..98. Llenamos los campos sin incluir la fecha de nacimiento
Línea 102. Se valida si el botón Guardar esta deshabilitado
src/CreateTwitchAccount.js … 58: function handleDisabledSaveButton() { 59: if(errors.length !== 0) { 60: return true 61: } 62: 63: const requiredFields = ["username", "password", "birthdate", "phone", "email"] 64: return requiredFields.filter(field => !values[field]).length !== 1 65: } … 88: <button type="submit" disabled={handleDisabledSaveButton()}>Guardar</button> 89: </form> …
Línea 59..61. Si existe un error de tipo usuario repetido o de formato, deshabilitamos botón
Línea 63..64. Si los campos obligatorios no están, deshabilitamos el botón. Ojo, esta implementación es solo a modo de prueba, ya existen soluciones de terceros
Línea 88. Ejecutamos la función en todo momento para habilitar o deshabilitar el botón
Una vez cubiertas las reglas de negocio podemos comenzar a diseñar, refactorizar, mejorar o agregar nuevas funcionalidades. Gracias a las pruebas nuestras aplicaciones son escalables, entendibles y fáciles de probar.