Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jamilhf/400b31a35e9739223d3cbf18adf35df9 to your computer and use it in GitHub Desktop.
Save jamilhf/400b31a35e9739223d3cbf18adf35df9 to your computer and use it in GitHub Desktop.
module.exports = function() {
Cypress.Commands.add('sqlServer', (query) => {
if(!query) {
throw new Error('Query must be set');
}
cy.task('sqlServer:execute', query).then(response => {
let result = [];
const flatten = r => Array.isArray(r) && r.length === 1 ? flatten(r[0]) : r;
if(response) {
for (let i in response) {
result[i] = [];
for (let c in response[i]) {
result[i][c] = response[i][c].value;
}
}
result = flatten(result);
} else {
result = response;
}
return result;
});
});
}
const Tedious = require('tedious');
module.exports = (dbConfig) => {
return {
'sqlServer:execute': (sql) => {
const connection = new Tedious.Connection(dbConfig);
return new Promise((res, rej) => {
connection.on('connect', err => {
if (err) {
rej(err);
}
const request = new Tedious.Request(sql, function(err, rowCount, rows) {
return err ? rej(err) : res(rows);
});
connection.execSql(request);
});
});
}
}
};
@Sarute
Copy link

Sarute commented Dec 2, 2020

Could you please tell me how do you declare it in index.js?

@jamilhf
Copy link
Author

jamilhf commented Dec 2, 2020

I ended up using different plugin I think this one worked for me what are you trying to do ? Run queries and pass those data in your tests ? Tasks was the option in Cypress

const sql = require('mssql');
module.exports = (on) => {

on('task', {

    queryDb: (query) => {
        console.log('Value from task : ' + query);

        return queryTestDb(query);
    },
   
});

};

constconfigDB = {
server: '',
port: ,
domain: '',
user: '',
password: '',
database: '',
requestTimeout: 300000,
driver: 'tedious',
options: {
enableArithAbort: true,
},
};

async function queryTestDb(query, config) {
await sql.connect(constconfigDB);

let sqlRequest = new sql.Request();
return new Promise((resolve, reject) => {
    sqlRequest.query(query, (error, results) => {
        if (error) reject(error);
        else {
            console.log(results);
            sql.close();
            return resolve(results);
        }
    });
});

}

@Sarute
Copy link

Sarute commented Dec 2, 2020

You save my day! your solution works for me!

@jamilhf
Copy link
Author

jamilhf commented Dec 2, 2020

awesome! i know it was pain couple days spent till I found this solution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment