Cypress task undefined even though the promise is returned

Tags: , , , ,



I used TypeScript and Cypress framework for the automation purpose. To retrieve the data from SQL Server I have tried with Cypress sql server but that is available only in JavaScript, due to that I have used the JavaScript MSSQL library to retrieve the values under plugin/index.js then called that function in the required TypeScript file. But it throws the error as undefined value during retrieval process even though I handled with promise. But the query output is successfully printed in the console (attached the image below)

I have tried the same with MYSQL there it works and in MSSQL it fails. What would be the reason, do I miss anything here? I have shared the trials and information below:

plugin/index.js

var mssql = require('mssql');

module.exports = (on, config) => {      
  on('task', {
    'createMSSQLConnection'(query) {
      var res = odsQueryDB(query)
      console.log(res)
      return res
    }
  });

function odsQueryDB(query) {
    return new Promise((resolve, reject) => {
      mssql.connect(db.ods,function(err){       
      if(err){ console.log(err) }
      var sqlServerRequest = new mssql.Request();
      sqlServerRequest.query(query, (error, recordset) => {
        if(error)  
          return reject(error)
        mssql.close();      
        console.log(recordset[0])
        return resolve(recordset)
       })
      })
    })
  }   
};

database.ts

class DBConnectionManager {

  getODSValueFromDB(){
      const query = `SELECT TOP(1) FIELD FROM TABLE`;
      cy.task('createMSSQLConnection',query).then(function (recordset:any) {
        if(recordset.length<1){
          throw new Error("There are no values in the results. Check the database data!")
        }
        let rec:any = recordset
        const results:any = Object.values(rec[0])
        cy.log(''+results[0])
   })
}

Console Output:

Console Output

Answer

The issue was with the database.ts during the data retrieval process. The record set was an array with the JSON format as below.

console

The below changes in the database.ts worked

class DBConnectionManager {

  getODSValueFromDB(){

    const query = `SELECT TOP(1) FIELD FROM TABLE`;

    cy.task('createMSSQLConnection',query).then(function (recordset:any) {
    if(recordset.length<1){
      throw new Error("There are no values in the results. Check the database data!")
    }
    else{
     //The below one is the modified one for the data retrieval
     cy.log(recordset['recordset'][0].FIELDNAME)  
    }
  })
}

The output in Cypress dashboard after the code change:

Console Left Pane



Source: stackoverflow