cypress 数据库插件

Dennis Zhang - Sep 11 - - Dev Community

1、MySQL

npm install mysql2
Enter fullscreen mode Exit fullscreen mode

配置 cypress.config.js

const mysql = require('mysql2/promise');

module.exports = (on, config) => {
  on('task', {
    async queryDatabase(query) {
      const connection = await mysql.createConnection({
        host: process.env.DB_HOST || 'localhost',
        user: process.env.DB_USER || 'root',
        password: process.env.DB_PASSWORD || 'password',
        database: process.env.DB_NAME || 'your_database',
      });

      const [results] = await connection.execute(query);
      return results;
    },
  });
};

Enter fullscreen mode Exit fullscreen mode
it('should query the database', () => {
  cy.task('queryDatabase', 'SELECT * FROM users').then((results) => {
    expect(results).to.have.length.greaterThan(0);
  });
});

Enter fullscreen mode Exit fullscreen mode

2、PostgreSQL

npm install pg

Enter fullscreen mode Exit fullscreen mode

配置 cypress.config.js

const { Client } = require('pg');

module.exports = (on, config) => {
  on('task', {
    async queryPostgres(query) {
      const client = new Client({
        host: process.env.PG_HOST || 'localhost',
        user: process.env.PG_USER || 'postgres',
        password: process.env.PG_PASSWORD || 'password',
        database: process.env.PG_DATABASE || 'your_database',
      });

      await client.connect();
      const res = await client.query(query);
      await client.end();
      return res.rows;
    },
  });
};
Enter fullscreen mode Exit fullscreen mode
it('should query the Postgres database', () => {
// task 参数来源于task注册的函数名
  cy.task('queryPostgres', 'SELECT * FROM users').then((results) => {
    expect(results).to.have.length.greaterThan(0);
  });
});

Enter fullscreen mode Exit fullscreen mode

db2

npm install ibm_db
Enter fullscreen mode Exit fullscreen mode

配置文件

const { defineConfig } = require("cypress");
const ibmdb = require("ibm_db");

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      // implement node event listeners here
      on("task", {
        queryDb2(query) {
          const connStr =
            "DATABASE=<your_db>;HOSTNAME=<your_host>;UID=<your_user>;PWD=<your_password>;PORT=<your_port>;PROTOCOL=TCPIP";

          return new Promise((resolve, reject) => {
            ibmdb.open(connStr, (err, conn) => {
              if (err) {
                reject(err);
                return;
              }

              conn.query(query, (err, data) => {
                if (err) {
                  reject(err);
                } else {
                  resolve(data);
                }
                conn.close();
              });
            });
          });
        }
      });
    }
  }
});


Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player