function always return undefined value in cypress

715 Views Asked by At

this is the cypress test file

import { Given, Then } from "cypress-cucumber-preprocessor/steps";
import { quickSignIn } from "../../../support/services/commonServices";
import { storyTableViewResultColumnCheck } from "../../../support/services/calculationStoryService";
    
    
    Given('Logged into the application', () => {
        quickSignIn(Cypress.env('username'), Cypress.env('password'));
    });
    
    Then('navigate to the story', () => {
        storyTableViewResultColumnCheck();
    });

this is calculationStoryService.js file

export function storyTableViewResultColumnCheck() {
        const stories =  getAllCalculationStoriesFromExcel(); // return undefined value
        expect(stories).not.to.be.undefined
        cy.log("method - storyTableViewResultColumnCheck",stories)
    }
    
function getAllCalculationStoriesFromExcel() {
        cy.task("getExcelData", Cypress.env("calculationRelatedStoryPath")).then((stories) => {
            console.log(stories) // in here print all the stories without any issue. 
            return stories;
        });
    }

when calling the "getAllCalculationStoriesFromExcel" method inside the "storyTableViewResultColumnCheck" method, it always returns undefined value. but console log inside the "then" block in the "getAllCalculationStoriesFromExcel" method print all the stories to the console.

I want to know how to return a value once cy.task is completed

enter image description here

2

There are 2 best solutions below

0
On

Cypress commands are asynchronous. So you cannot directly return a value from a command (including cy.task one). Moreover, your function returns nothing as it does not declare the return statement. In order to synchronize the execution flow, you can use a then callback:

function getAllCalculationStoriesFromExcel() {
        return cy.task("getExcelData", Cypress.env("calculationRelatedStoryPath")).then((stories) => {
            console.log(stories) // in here print all the stories without any issue. 
            return stories;
        });
    }
export function storyTableViewResultColumnCheck() {
    getAllCalculationStoriesFromExcel().then(stories => {
        expect(stories).not.to.be.undefined
        cy.log("method - storyTableViewResultColumnCheck",stories)
    })
}
0
On

You can add a Promise wrapper to make it work

export async function storyTableViewResultColumnCheck() {
  const stories = await getAllCalculationStoriesFromExcel(); 
  expect(stories).not.to.be.undefined
  cy.log("method - storyTableViewResultColumnCheck",stories)
}
    
function getAllCalculationStoriesFromExcel() {
  return new Promise(resolve => {
    cy.task("getExcelData", Cypress.env("calculationRelatedStoryPath"))
      .then((stories) => resolve(stories))
  })
}