首页 > 解决方案 > Cypress 中与 SQLite 数据库的示例数据库连接

问题描述

我之前在连接到 SQLite 数据库时遇到了问题。现在我想通了,我想与大家分享解决方案。谢谢。

在插件/index.js


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

也在 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
    
        });
    }

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)
          }
          
          });
           
      }) 
    
      })

标签: databasesqlitepromisecypress

解决方案


可能与 cypress 5.3.0 中的错误修复有关:“修复了未传递参数的 cy.task 将接收 null 作为第一个参数而不是未定义的问题” https://docs.cypress.io/guides/references/更改日志.html#5-3-0


推荐阅读