Soy nuevo en cypress+TS. No puedo devolver un valor dentro del bucle each en Cypress con Typescript
No se puede devolver un valor dentro de cada bucle en Cypress con Typescript. El valor de patientBalance es indefinido.
Código de la clase principal
let patientBalance: number = getPatientBalance(claimNumber);
Función como abajo:
let amountInDollar1: string[];
let amount1: number;
export let getPatientBalance = (claimNumber: string) => {
getClaimNumberCells().each((input, index) => {
const claimText = input.text();
getChargesTable().scrollTo('right');
if (claimText.includes(claimNumber)) {
getPatientBalanceCell()
.eq(index)
.each((data) => {
amountInDollar1 = data.text().split('$');
amount1 = parseFloat(amountInDollar[1]);
console.log('Amount in loop', +amount1);
});
}
});
return amount1;
};
Además, quiero usar este patientBalance en varios puntos a lo largo de la prueba. ¿Cómo puedo asignar este valor a una variable?
Respuesta #1
El comando .each() es asincrónico, por lo que no puedes devolver de forma síncrona como has intentado hacer.
Creo que agregar algunas llamadas a .then() debería hacer lo que quieres hacer:
export let getPatientBalance = (claimNumber: string) => {
getClaimNumberCells().each((input, index) => {
// calculate
})
return cy.then(() => { // returning the cy.then() ensures async completed
// option 1 - put value in an alias for multiple use in same test
cy.wrap(amount1).as('oldPatientBalance') // an alias stores the value
// option 2 - put value in an env variable for use across multiple tests
Cypress.env('oldPatientBalance', amount1)
// option 3 - return the value directly
return amount1 // or direct return of value
})
})
// In test(s)
// option 3 - use the returned value
getClaimNumberCells().then(amount1 => {
// use it here
})
// option 1 - take the value from the alias later in the same test
cy.get('@oldPatientBalance').then(oldPatientBalance => {
console.log('oldPatientBalance', oldPatientBalance);
}
// option 2 - should be accessible in other tests (not same test)
it('another test for where amount is calculated', () => {
const oldPatientBalance = Cypress.env('oldPatientBalance')
})
