Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

javascript - Cypress task undefined even though the promise is returned

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

question from:https://stackoverflow.com/questions/65847239/cypress-task-undefined-even-though-the-promise-is-returned

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The whole point of callbacks is that you don't have to return values anymore, just call the callbacks, giving the required info as parameter(s).

So, change this line:

return resolve(recordset)

To this instead:

resolve(recordset);

And it should work fine.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...