无cypress.json时如何配置Cypress 10.8.0的cypress-sql-server插件
解决Cypress 10.8.0中cypress-sql-server插件的配置错误
问题背景
使用Cypress 10.8.0版本集成cypress-sql-server插件时,因该版本已废弃cypress.json配置文件,沿用旧教程配置后运行测试出现cy.task('sqlServer:execute')未注册的错误。
错误信息
tasksqlServer:execute, SELECT 'Bob' CypressError cy.task('sqlServer:execute') failed with the following error: The 'task' event has not been registered in the setupNodeEvents method. You must register it before using cy.task() Fix this in your setupNodeEvents method here: D:\git\mcare.automation\client\cypress\cypress.config.jsLearn more node_modules/cypress-sql-server/src/commands/db.js:7:1 5 | } 6 | > 7 | cy.task('sqlServer:execute', query).then(response => { | ^ 8 | let result = []; 9 |
当前配置代码
cypress.config.js
const { defineConfig } = require("cypress"); const sqlServer = require("cypress-sql-server"); module.exports = defineConfig({ e2e: { setupNodeEvents(on, config) { // allows db data to be accessed in tests config.db = { "userName": "user", "password": "pass", "server": "myserver", "options": { "database": "mydb", "encrypt": true, "rowCollectionOnRequestCompletion": true } } // code from /plugins/index.js const tasks = sqlServer.loadDBPlugin(config.db); on('task', tasks); return config // implement node event listeners here }, }, });
测试文件 testSQL.spec.js
describe('Testing SQL queries', () => { it("It should return Bob", () => { cy.sqlServer("SELECT 'Bob'").should('eq', 'Bob'); }); })
解决方案
1. 升级插件确保版本兼容
先将cypress-sql-server升级到最新版本,适配Cypress 10+架构:
npm install cypress-sql-server@latest --save-dev
2. 手动导入自定义命令
Cypress 10+需手动在支持文件中导入插件的自定义命令,在cypress/support/e2e.js中添加以下代码:
require('cypress-sql-server/src/commands/db');
3. 修正测试断言逻辑
cy.sqlServer()返回的是结果集数组,而非直接的字符串值,需调整断言逻辑提取目标值:
describe('Testing SQL queries', () => { it("It should return Bob", () => { cy.sqlServer("SELECT 'Bob'").then(queryResult => { // 提取结果集中的第一个字段值 expect(queryResult[0]['']).to.equal('Bob'); }); }); })
4. 确认配置文件有效性
保持cypress.config.js中setupNodeEvents的数据库配置和任务注册代码不变,确保on('task', tasks)正确注册了sqlServer:execute任务,且返回了修改后的config对象。
验证步骤
- 重启Cypress测试 runner
- 运行
testSQL.spec.js测试用例 - 确认测试通过,SQL查询结果正确返回
内容的提问来源于stack exchange,提问作者dcoughler
相关产品推荐
相关产品推荐

