Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can i make a mysql connection in cypress ? #3689

Closed
vcamposs opened this issue Mar 12, 2019 · 34 comments
Closed

Can i make a mysql connection in cypress ? #3689

vcamposs opened this issue Mar 12, 2019 · 34 comments

Comments

@vcamposs
Copy link

vcamposs commented Mar 12, 2019

Hello.
I need make a mysql connection in cypress, but i have some problems.

I used this simple code (after install npm mysql):

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
});

And this error was returned :
-- TypeError: Net.createConnection is not a function

Is possible do that in cypress ? There are some alternative ?

Ps.: I used the same code in other project with node.js, and run with sucess.

Help me =))

@vcamposs vcamposs changed the title I cant make mysql a connection in cypress ? I cant make a mysql connection in cypress ? Mar 12, 2019
@vcamposs vcamposs changed the title I cant make a mysql connection in cypress ? cant I make a mysql connection in cypress ? Mar 12, 2019
@vcamposs vcamposs changed the title cant I make a mysql connection in cypress ? Cant i make a mysql connection in cypress ? Mar 12, 2019
@vcamposs vcamposs changed the title Cant i make a mysql connection in cypress ? Can i make a mysql connection in cypress ? Mar 12, 2019
@bahmutov
Copy link
Contributor

Since this is backend connection, it cannot be done from the spec.js file which executes in the browser. Use cy.task to execute your code, see https://on.cypress.io/task

@vcamposs
Copy link
Author

vcamposs commented Mar 12, 2019

@bahmutov do you have a sample of db conection ?

@bahmutov
Copy link
Contributor

bahmutov commented Mar 12, 2019 via email

@vcamposs
Copy link
Author

vcamposs commented Mar 12, 2019

Really @bahmutov ! Run here ! Tks

@SUSANO-O
Copy link

hello a question can I test my back-end of my application? Thank you

@SUSANO-O
Copy link

hello
I would like to know if you can help me, of course, it's like entering the backend of my app, let's say; create a product and I want to know if a property of my idproduct object reacted to the new value. Can this be valued with cypress? thanks for your time

@jennifer-shehane
Copy link
Member

@SUSANO-O Check out our community chat, it can be helpful for debugging or answering questions on how to use Cypress.

@jennifer-shehane
Copy link
Member

​I recently found this utility called cypress-sql-server which may be helpful for connecting to an SQL database.

I have not tried this code myself, so I would take care and inspect the code they are executing. I downloaded it and found the following code they're using. https://gist.github.com/jennifer-shehane/f498ce68b46425583fa72c8d945fe7bb

@popescunsergiu
Copy link

popescunsergiu commented Aug 21, 2019

@bahmutov you are really helpful.
Trying to connect to a mysql instance to get test data from with no luck and documentation pointed by you does not help.
Thank you

@jennifer-shehane the plugin pointed does not work. More than this, I found that adding tree structure under cypress.[ENV].json file makes cypress fail with: Cannot set X of undefined

@you1anna
Copy link

you1anna commented Oct 8, 2019

@jennifer-shehane cypress-sql-server does not work, having run the configuration they suggest the error in Cypress is

Error:     CypressError: cy.task('sqlServer:execute') failed with the following error:`
TypeError: No connection configuration given

Have seen similar reported on StackOverflow.

@katerynaaivanova
Copy link

katerynaaivanova commented Oct 31, 2019

@you1anna I've managed to resolve this error by moving db configuration inside "env" part in cypress.json.

"env": {
"db": {
    "userName": "",
    "password": "",
    "server": "",
    "options": { }
}
}

Aslo you'll need to update cypress/plugins/index.js

tasks = sqlServer.loadDBPlugin(config.env.db);  

However, it seems that the cypress-sql-server plugin works only with MS SQL db, as it uses Tedious library for connection, so it won't be working with MySQL.

@emereyd
Copy link

emereyd commented Nov 26, 2019

For those with a mysql db the following code works for me using the mysql lib :

in cypress.json add the db details to env object:

"db": {
      "host": "your-host",
      "user": "your-username",
      "password": "your-pwd"
    }

in plugins/index.js:

const mysql = require('mysql')
function queryTestDb(query, config) {
  // creates a new mysql connection using credentials from cypress.json env's
  const connection = mysql.createConnection(config.env.db)
  // start connection to db
  connection.connect()
  // exec query + disconnect to db as a Promise
  return new Promise((resolve, reject) => {
   connection.query(query, (error, results) => {
      if (error) reject(error)
      else {
        connection.end()
        // console.log(results)
        return resolve(results)
      }
    })
  })
}

module.exports = (on, config) => {
  // Usage: cy.task('queryDb', query)
  on('task', {
    queryDb: query => {
      return queryTestDb(query, config)
    },
  })
}

Hope this helps. If you are still having issue, it might be your connection credentials?

@MehranShafqat
Copy link

MehranShafqat commented Feb 10, 2020

@emereyd well im still having issues and I follow the same steps as you mentioned.

TypeError: Cannot read property 'host' of undefined
    at new ConnectionConfig 

look like its not able to get the connection data from cypress.json file

@wagnermduarte
Copy link

@emereyd well im still having issues and I follow the same steps as you mentioned.

TypeError: Cannot read property 'host' of undefined
at new ConnectionConfig

look like its not able to get the connection data from cypress.json file

I had the same problem.

@wagnermduarte
Copy link

wagnermduarte commented Feb 11, 2020

I understand the problem, we need to put the env object like this

  "env":{
  "db": {
    "host": "base",
    "user": "test",
    "password": "secret",
    "database": "there"
    }
  }

@amaedo
Copy link

amaedo commented Feb 20, 2020

The previous setting is working for me provided by @emereyd, can somebody provide a working example of some assertion using the previous MySQL connection setting in cypress?

@you1anna
Copy link

you1anna commented Feb 20, 2020

cypress.json:

{
  "baseUrl": "https://f.dev/",
  "pageLoadTimeout": 50000,
  "requestTimeout": 50000,
  "defaultCommandTimeout": 50000,
  "responseTimeout": 50000,
  "waitForAnimations": true,
  "viewportWidth": 1280,
  "viewportHeight": 800,
  "chromeWebSecurity": false,
  "env": {
    "db": {
      "host": "127.0.0.2",
      "user": "xxx",
      "password": "yyy",
      "database": "zz"
    }
  },
  "reporter": "cypress-multi-reporters",
  "reporterOptions": {
    "configFile": "reporterOpts.json"
  }
}

cypress/plugins/index.js

const mysql = require('mysql')

function queryTestDb(query, config) {
  const connection = mysql.createConnection(config.env.db)
  connection.connect()
  return new Promise((resolve, reject) => {
    connection.query(query, (error, results) => {
      if (error) reject(error)
      else {
        connection.end()
        return resolve(results)
      }
    })
  })
}

Code

cy.task('queryDb', 'DELETE FROM `sometable`')

@amaedo
Copy link

amaedo commented Feb 20, 2020

ok, but how do you use it to do an assertion
Like: cy.task('queryDb', 'SELECT FROM sometable').should(‘be.equal’,”somevalue”);

@amaedo
Copy link

amaedo commented Feb 20, 2020

in the previous config I had some issue but was fixed by doing this: https://stackoverflow.com/questions/50093144/mysql-8-0-client-does-not-support-authentication-protocol-requested-by-server

@emereyd
Copy link

emereyd commented Feb 20, 2020

You need to use .then (see https://docs.cypress.io/api/commands/then.html#Usage)
to get the results.

Inside the then you can do some assertions.

e.g.

cy.task('queryDb', `YOUR_QUERY_GOES_HERE`)
      .then(results => {
        expect(results).to.have.lengthOf(1)
      })

@Jacek-fstack
Copy link

Jacek-fstack commented Apr 2, 2020

Was anyone able to connect to DB that uses SSH connection?
I'm getting ERRCONREFUSED every time.

@skunique123
Copy link

skunique123 commented Apr 10, 2020

Getting Below Error
CypressError: cy.task('queryDb') failed with the following error:

Error: ER_NO_DB_ERROR: No database selected
at Query.Sequence._packetToError
Used below query
cy.task('queryDb', 'SELECT ename FROM employee').then(results => {
expect(results).to.have.lengthOf(1)

Index.js

/**
 * @type {Cypress.PluginConfig}
 */
const mysql = require('mysql')
function queryTestDb(query, config) {
  const connection = mysql.createConnection(config.env.db)
  connection.connect()
  return new Promise((resolve, reject) => {
   connection.query(query, (error, results) => {
      if (error) reject (error)
      else {
        connection.end()
         console.log(results)
         cy.log("connected")
        return resolve(results)
      }
    })
  })
}
 module.exports = (on, config) => {
   on('task', {
     queryDb: query => {
       return queryTestDb(query, config)
     },
   })
 }

@shahmed-nisum-com
Copy link

shahmed-nisum-com commented May 7, 2020

I am using mysql to connect in cypress I used following code in my project:

In my spec file i used these line in It block:

cy.task('queryDb', 'SELECT FROM `bank`').then(res => {
      expect(res).to.have.lengthOf(150);
    });

I have used following dependencies:

 "cypress-sql-server": "^1.0.0",
 "tedious": "^8.3.0"

In plugin file i added following code:

const mysql = require('mysql');
function queryTestDb(query, config) {
  // creates a new mysql connection using credentials from cypress.json env's
  const connection = mysql.createConnection(config.env.db);
  // start connection to db
  connection.connect();
  // exec query + disconnect to db as a Promise
  return new Promise((resolve, reject) => {
   connection.query(query, (error, results) => {
      if (error) reject(error)
      else {
        connection.end();
        // console.log(results)
        return resolve(results);
      }
    });
  });
}

module.exports = (on, config) => {
  // Usage: cy.task('queryDb', query)
  on('task', {
    queryDb: query => {
      return queryTestDb(query, config);
    },
  });
};

Cypress.json i used following code;

"env":{
        "db":{
            "host": "localhost",
            "user":"root",
            "password":"root",
            "database":"donation"
        }
    }

After executing code i get following error message please help me out in this regards:
The plugins file is missing or invalid.

Your `pluginsFile` is set to `E:\cypress24\cypress\plugins\index.js`, but either the file is missing, it contains a syntax error, or threw an error when required. The `pluginsFile` must be a `.js` or `.coffee` file.

Or you might have renamed the extension of your `pluginsFile` to `.ts`. If that's the case, restart the test runner.

Please fix this, or set `pluginsFile` to `false` if a plugins file is not necessary for your project.

 Error: Cannot find module 'mysql'
Require stack:
- E:\cypress24\cypress\plugins\index.js
- C:\Users\shahmed\AppData\Local\Cypress\Cache\4.4.1\Cypress\resources\app\packages\server\lib\plugins\child\run_plugins.js
- C:\Users\shahmed\AppData\Local\Cypress\Cache\4.4.1\Cypress\resources\app\packages\server\lib\plugins\child\index.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:798:15)
    at Module._load (internal/modules/cjs/loader.js:691:27)
    at Module._load (electron/js2c/asar.js:717:26)
    at Function.Module._load (electron/js2c/asar.js:717:26)
    at Module.require (internal/modules/cjs/loader.js:853:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (E:\cypress24\cypress\plugins\index.js:18:15)
    at Module._compile (internal/modules/cjs/loader.js:968:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:986:10)
    at Module.load (internal/modules/cjs/loader.js:816:32)
    at Module._load (internal/modules/cjs/loader.js:728:14)
    at Module._load (electron/js2c/asar.js:717:26)
    at Function.Module._load (electron/js2c/asar.js:717:26)
    at Module.require (internal/modules/cjs/loader.js:853:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at module.exports (C:\Users\shahmed\AppData\Local\Cypress\Cache\4.4.1\Cypress\resources\app\packages\server\lib\plugins\child\run_plugins.js:206:15)
PS E:\cypress24>

@LeonoraFernandes
Copy link

LeonoraFernandes commented May 22, 2020

@you1anna I've managed to resolve this error by moving db configuration inside "env" part in cypress.json.

"env": {
"db": {
    "userName": "",
    "password": "",
    "server": "",
    "options": { }
}
}

Aslo you'll need to update cypress/plugins/index.js

tasks = sqlServer.loadDBPlugin(config.env.db);  

However, it seems that the cypress-sql-server plugin works only with MS SQL db, as it uses Tedious library for connection, so it won't be working with MySQL.

I wanted help on full configuration of Microsoft SQL Server Database connection in Cypress...! @jennifer-shehane @you1anna

@prnab
Copy link

prnab commented Aug 13, 2020

ou are still having issue, it might be you

Dear, the code is working fine. Can u give me the code for accessing Db for different environment

@sarita555
Copy link

sarita555 commented Aug 27, 2020

Hi,
my SSL connection to mysql is not working. Please let me know what i need to add or update to connect to database with SS tunnel below

"env":{
"db":{
"host": "127.0.0.1",
"user": "",
"password": "**",
"database": "charger_db"

  }
},

plugin:

const mysql = require('mysql')
function queryTestDb(query, config) {
// creates a new mysql connection using credentials from cypress.json env's
const connection = mysql.createConnection(config.env.db)
// start connection to db
connection.connect()
// exec query + disconnect to db as a Promise
return new Promise((resolve, reject) => {
connection.query(query, (error, results) => {
if (error) reject(error)
else {
connection.end()
// console.log(results)
return resolve(results)
}
})
})
}

module.exports = (on, config) => {
// Usage: cy.task('queryDb', query)
on('task', {
queryDb: query => {
return queryTestDb(query, config)
},
})
}

mySQL:

image

Leave a comment

@prnab
Copy link

prnab commented Aug 31, 2020 via email

@sarita555
Copy link

sarita555 commented Aug 31, 2020 via email

@sarita555
Copy link

sarita555 commented Aug 31, 2020 via email

@Anju012345
Copy link

Anju012345 commented Dec 9, 2020

I was trying to connect to Mysql DB from cypress, did the following steps for the same.

Step 1: Added MySQL library in cypress

Step 2: Added following code in plugins/index.js file (This I have got while searching in google)

const mysql = require('mysql')
function queryTestDb(query, config) {
  // creates a new mysql connection using credentials from cypress.json 
env's
  const connection = mysql.createConnection(config.env.db)
  // start connection to db
  connection.connect()
  // exec query + disconnect to db as a Promise
  return new Promise((resolve, reject) => {
   connection.query(query, (error, results) => {
      if (error) reject(error)
      else {
        connection.end()
        // console.log(results)
        return resolve(results)
      }
    })
  })
}

module.exports = (on, config) => {
  // Usage: cy.task('queryDb', query)
  on('task', {
    queryDb :query =>  {
      return queryTestDb(query, config)
    },
  })
}

Step 3: Added the following dependencies in cypress.json

"env" : {
      "db": {
        "host": "name",
        "user": "user",
        "password": "password"
      }
    }

Step 4: Added the following code in the spec.js file

it('Verify the retrieved data', () => {
    cy.task('queryDb','select * from soandso where soandso = value').then((resp) => {
        console.log(resp.rows)
      })
  })

But while running the spec file getting the below error

cy.task('queryDb') failed with the following error: > ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client

Please help me to fix this error. Thanks in advance. @jennifer-shehane

@jennifer-shehane
Copy link
Member

You may want to try asking our community in our GitHub Discussions. As an open source project with a small maintainer team we have to focus our time on bugs and features in the product, which Issues are reserved for.

@chaz2k
Copy link

chaz2k commented May 28, 2021

Hi,
I added the code in the appropriate files as described by Anju012345 above, and I'm receiving the following error which doesn't really give me a clue on how to fix it:

spec command:
cy.task("queryDB", select id from wp_posts where post_title = 'chaz hl test version control' and post_modified like '2021-05-26%';)

CypresError:

cy.task('queryDB') failed with the following error:

The task 'queryDB' was not handled in the plugins file. The following tasks are registered: queryDb

Fix this in your plugins file here:
/Users/cchoy/Documents/workspace/core-automation/frontend_automation/cypress/plugins/index.js

Note: Using the connection info in cypress.json ( will not show the values here since it's proprietory), I was able to connect to our staging db using node's command line interface.

@emereyd
Copy link

emereyd commented Jun 9, 2021

@chaz2k Are you still having issues with this?
Looking at the error msg .task might be case sensitive. i.e. queryDB vs queryDb.

@chaz2k
Copy link

chaz2k commented Jun 10, 2021

Hi @emereyd Thank you very much for checking, I actually got the the queryDB working. Cheers!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests