1、MySQL
npm install mysql2
配置 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;
},
});
};
it('should query the database', () => {
cy.task('queryDatabase', 'SELECT * FROM users').then((results) => {
expect(results).to.have.length.greaterThan(0);
});
});
2、PostgreSQL
npm install pg
配置 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;
},
});
};
it('should query the Postgres database', () => {
// task 参数来源于task注册的函数名
cy.task('queryPostgres', 'SELECT * FROM users').then((results) => {
expect(results).to.have.length.greaterThan(0);
});
});
db2
npm install ibm_db
配置文件
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();
});
});
});
}
});
}
}
});