[英]How to stub a database query in Cypress?
I am trying to write an end-to-end integration test using Cypress.我正在尝试使用赛普拉斯编写端到端集成测试。 The flow involves querying a database.
该流程涉及查询数据库。 We want to stub the database call and return a static JSON object that will test every scenario.
我们想要存根数据库调用并返回一个 static JSON object 来测试每个场景。 Is there a way for me to do that with Cypress?
我有办法用赛普拉斯做到这一点吗?
The database query method:数据库查询方法:
export class myClass {
constructor(private readonly connector: MssqlConnector) {
super();
}
async myQuery() {
const pool = await this.connector.getConnectionPool();
const response = await pool.query(q));
return response.recordset;
}
}
You can do this using cy.task您可以使用 cy.task 执行此操作
// in test
const dbName = 'stagingA'
const query = 'SELECT * FROM users'
cy.task('queryDatabase', { dbName, query })
// in plugins/index.js
const mysql = require('mysql')
// the connection strings for different databases could
// come from a config file, or from environment variables
const connections = {
stagingA: {
host: 'staging.my.co',
user: 'test',
password: '***',
database: 'users'
},
stagingB: {
host: 'staging-b.my.co',
user: 'test',
password: '***',
database: 'users'
}
}
// querying the database from Node
function queryDB (connectionInfo, query) {
const connection = mysql.createConnection(connectionInfo)
connection.connect()
return new Promise((resolve, reject) => {
connection.query(query, (error, results) => {
if (error) {
return reject(error)
}
connection.end()
return resolve(results)
})
})
}
module.exports = (on, config) => {
on('task', {
// destructure the argument into the individual fields
queryDatabase ({ dbName, query }) {
const connectionInfo = connections[dbName]
if (!connectionInfo) {
throw new Error(`Do not have DB connection under name ${dbName}`)
}
return queryDB(connectionInfo, query)
}
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.