Not able to return a value inside each loop in Cypress with Typescript. patientBalance
value is undefined.
Main class code
let patientBalance: number = getPatientBalance(claimNumber);
Function as below:
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;
};
Also, I want to use this patientBalance
at multiple points throughout the test. How can I assign this value to a variable?
The .each()
command is asynchronous, so you can't return synchronously as you have tried to do.
I think adding some .then()
calls should do what you want to do:
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')
})