ฉันเป็นมือใหม่กับ cypress+TS ไม่สามารถคืนค่าภายในลูป each ใน Cypress กับ Typescript ได้
ไม่สามารถส่งค่ากลับภายในลูปแต่ละรอบใน Cypress กับ Typescript ได้ ค่า patientBalance เป็น undefined
โค้ดคลาสหลัก
let patientBalance: number = getPatientBalance(claimNumber);
ฟังก์ชันดังนี้:
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;
};
นอกจากนี้ ฉันต้องการใช้ patientBalance นี้ในหลายจุดตลอดการทดสอบ ฉันสามารถกำหนดค่านี้ให้กับตัวแปรได้อย่างไร?
คำตอบ #1
คำสั่ง .each() เป็นแบบอะซิงโครนัส ดังนั้นคุณจึงไม่สามารถส่งค่ากลับแบบซิงโครนัสได้เหมือนที่คุณพยายามทำ
ฉันคิดว่าการเพิ่มการเรียก .then() บางส่วนควรจะทำให้สิ่งที่คุณต้องการทำได้:
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')
})
