https://cypress.io logo
Microsoft SQL Server Management Studio connection ...
# i-need-help
c
Hello All, I need to verify table entries after performing few actions from UI in Microsoft SQL Server Mgmt. So could you please provide any reference Doc or Any Video link for e2e connection with this Database ?
l
Hi there! I'll try to help you shortcut this by just pasting what I use. Discord is telling me this is too long, so I'll make it a two-parter. First, install the mssql Node package: https://www.npmjs.com/package/mssql Next, some Node code to execute a SQL statement. In a file called `plugins/db_exec_sql_statement.js`:
Copy code
js
const sql = require('mssql')

static customerDb = {
  user: 'userNameHere',
  password: 'passwordHere',
  server: 'serverNameHere', // You can use 'localhost\\instance' to connect to named instance
  database: 'dbNameHere',
}

module.exports = (statement, config) => {
  return new Promise(async function (resolve, reject) {
    console.log('***')
    console.log(statement)
    console.log('***')

    const connectToDb = async (config) => {
      try {
        const pool = await sql.connect(config)
        console.log('Connected to database')
        return pool
      } catch (err) {
        console.log('Error connecting to database: ', err)
      }
    }

    const execute = async (pool, query) => {
      try {
        const result = await pool.request().query(query)
        console.log(result)
        return result
      } catch (err) {
        console.log('Error executing query: ', err)
      }
    }

    const closeDb = async (pool) => {
      try {
        await pool.close()
        console.log('Connection closed')
      } catch (err) {
        console.log('Error closing connection: ', err)
      }
    }

    const pool = await connectToDb(config)
    const result = await execute(pool, statement)
    await closeDb(pool)
    resolve(result)
  })
}
Here's the example code for the Cypress task, in
plugins/index.js
(or import it from a neighboring file, up to you):
Copy code
js
const execSqlStatement = require('./db_exec_sql_statement')

function fetchCustomerId(email) {
  const statement = `select customer_id from customer where email_address = '${email}'`
  return new Promise((resolve) => {
    execSqlStatement(statement, customerDb).then((result) => {
      resolve(result.recordset[0].customer_id)
    })
  })
}

module.exports = (on) => {
  on('task', {
    fetchCustomerId,
  })
}
And lastly, the usage in a test:
Copy code
js
cy.task('fetchCustomerId', 'mrt@example.com').then((customerId) => {
  cy.log(customerId)
}
c
Thanks @late-planet-4481 !!!
31 Views