Search code examples
sql-servernode.jsselenium-webdriverprotractor

Protractor querying SQL Server database (MSSQL)


I am trying to execute a simple query on SQL Server but when I run it with protractor it just runs quickly and doesnt return (log) anything. I would appreciate any hints, working examples or pointers to what I am doing wrong and how to exec a SQL query on SQL Server with protractor.

var sql = require('mssql');

describe('test db connection', function () {

  it('tests db connection', function () {

    ConnectDB()

  })

  function ConnectDB() {

    var config = {
      user: 'user',
      password: 'password',
      server: 'xyz.database.windows.net',
      database: 'dbdev',

      options: {
        encrypt: true
      }
    }

    var connection = new sql.Connection(config)
    connection.connect(function (err) {
      console.log(err)
    })

    var request = new sql.Request(connection);
    request.query('select * from Config where [Key] like \'HidePreop%\'', function (err, recordeset) {
      var res = recordeset;
      console.log(res)
    });

Solution

  • Protractor test - it blocks will only wait for webDriverJS commands in Protractor control flow to finish and any other async activity you have to manually make the it block wait using done.

    In this case -

    describe('test db connection', function () {    
        it('tests db connection', function (done) {
            // Any method that returns a promise. Similary if your method returns a callback you can handle accordingly
            ConnectDB().then(function _onSuccess(){
                done();
            }).catch(function _onFailure(err){
                done.fail(err);
            })
        })
    });
    

    And I would modify your funcion - ConnectDB() to return a promise based on the resolution of the callback provide by the mssql npm package. Refer here on how to convert a callback to Promises. its an awesome tutorial.

    function ConnectDB() {
        return new Promise(function (fulfill, reject) {
            var config = {
                user: 'user',
                .............
            };
            var connection = new sql.Connection(config);
            connection.connect(function (err) {
                reject(err);
            });
    
            var request = new sql.Request(connection);
            request.query('select * from Config where [Key] like \'HidePreop%\'', function (err, recordeset) {
                if (err) reject(err);
                else fulfill(recordeset);
            });
        });
    }