How to do database integration with Cypress?

Reading Time: 2 minutes

Cypress is one of those popular tools which has established its place very quickly and is very popular for Web integration and End to End UI test automation. Cypress can do database integration. It needs a javascript framework like jasmine or mocha. These are one of the famous assertion libraries in JavaScript. Cypress recommends using mocha. In this blog, we will see how to do database integration using Cypress. Here we will integrate mysql plugin with Cypress. MySQL is an open-source relational database management system.

How to install mysql on Ubuntu?

You can refer to the link given in the references to install mysql.

How to perform database action using cypress?

Step 1: Install Mysql using command npm i mysql

After installing MySql, it should be showing up in the package.json file

Step 2: Let’s connect to our database using the MySQL plugin. Go to cypress/plugins/index.js and write the following code. Here, keep in mind that const connection is loading DB from env object.

Step 3: Let us connect Cypress with our database. Add the following code in cypress.json file

"db": {
      "host": "127.0.0.1",
      "user": "YOUR_USERNAME",
      "password": "YOUR_PASSWORD"
    }

Step 4: Now, we will be using cy.task() to enable cypress to run SQL queries. Let’s go to cypress/plugins/index.js and write the following code

Step 5: Now the connection has been established. It is time to perform some actions on the table. We will create a table by using the following code.

Step 6: Finally, execute the test case.

Step 7: If we want to run assertion. We can take the example of the following code.

cy.task(
      "queryDb",
      `SELECT * FROM SCHEMA_NAME.TABLE_NAME WHERE COLUMNS_NAME='VALUE'`
    ).then(count => {
      expect(count).to.have.lengthOf(1);
    });

Hope you all enjoyed doing database integration using Cypress.

References

https://phoenixnap.com/kb/install-mysql-ubuntu-20-04

Written by 

I work with Knoldus and have experience of 8+ years in quality assurance I have good experience on SeleniumWebdriver(C#), Selenium IDE, Nightwatch,Appium, Jira, TFS, ZAP, Fiddler, Jmeter, Jenkins, Selenium Webdriver. I am also ITIL certified.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading