Sample Database Connection to SQLite Database in Cypress

1k views Asked by At

I ran into an issue when connecting to a SQLite Database before. Now that I figured it out, I'd like to share the solution with everyone. Thanks.

In plugins/index.js


    const sqlite3 = require('sqlite3').verbose();
    module.exports = (on, _config) => {
        on('task', {
             queryDb: queryTestDb,
             //wait: timeout,
        });
    };

Also in plugins/index.js


    const path='C:/Users/Mamga/TestDB/chinook.db'
    function queryTestDb(sql) {
        let db = new sqlite3.Database(path);
        return new Promise((resolve, reject) => {
            db.all(sql, [], (err, rows) => {
            if(err) 
                reject(err); 
    
            else  {
              db.close();
              console.log(rows)
              return resolve(rows);
            }//End else
            
          });//End db.run
    
        });
    }

Actual Test in TaskCommandDBConnectionTest.js ///


    /// <reference types="Cypress" />
    describe('Task Command', () => {
      it('Should send execute something on node', () => {
        const query='select * from Persons';
        cy.task('queryDb', query).then((rows) => {
          //expect(rows).to.have.lengthOf(4);
          for(var i=0; i<rows.length; i++)
          {
            cy.log(rows[i].FirstName + " "+ rows[i].LastName + " " + rows[i].Age)
          }
          
          });
           
      }) 
    
      })
1

There are 1 answers

1
MrWrangler On

Might be related to a bugfix in cypress 5.3.0: "Fixed an issue where a cy.task with no arguments passed would receive null as the first argument instead of undefined" https://docs.cypress.io/guides/references/changelog.html#5-3-0