return a value from a function in cypress
import {StudentDetails} from "../Department"
let studentInfo = new StudentDetails();
let studName: any = '';
it('Get Student Name', function(){
studentInfo.getStudName();
studName = studentInfo.getStudName();
cy.log(studName);
})
Department file:
export class StudentDetails{
getStudName(){
cy.get('app-screen').find('input[id="studentName"]').invoke('val').as('name')
cy.get('@name').then((name) => {
cy.log('Student Name: ' + name)
return name
})
}
The above script doesn't return the student name. Instead it showing the below error. Could someone please help to sort this issue out?
cy.then() failed because you are mixing up async and sync code. In your callback function you invoked 1 or more cy commands but then returned a synchronous value.
Cypress commands are asynchronous and it doesn't make sense to queue cy commands and yet return a synchronous value.
You likely forgot to properly chain the cy commands using another cy.then().
As it says you can't just return a value from this in a synchronous way.
You should be returning the whole chain and use then
in the test itself.
getStudName(){
return cy.get('appscreen').find('input[id="studentName"]').invoke('val')
}
it('Get Student Name', function(){
studentInfo.getStudName().then((name) => {
cy.log('Student Name: ' + name)
})
})