使用Cypress+Cucumber跨域登录时cy.origin报错:on仅接受Function实例
解决Cypress+Cucumber跨域登录时cy.origin抛出"on only accepts instances of Function"错误
错误根源分析
这个错误通常由以下几个原因导致:
- 配置冲突:同时开启
chromeWebSecurity: false和experimentalSessionAndOrigin: true,两者会干扰跨域逻辑的正常执行 - Cucumber预处理器版本不兼容:使用旧版
cypress-cucumber-preprocessor(而非官方推荐的@badeball/cypress-cucumber-preprocessor),不支持cy.origin等新特性 - 回调函数上下文问题:Cucumber步骤使用普通
function定义,与cy.origin的箭头函数回调存在上下文绑定冲突
具体解决方案
1. 修复Cypress配置文件冲突
修改cypress.config.js,移除或关闭chromeWebSecurity(默认值为true),因为experimentalSessionAndOrigin已足够处理跨域场景:
module.exports = defineConfig({ projectId: "t7unhv", e2e: { setupNodeEvents(on, config) { on('task', { log(message) { console.log(message +'\n\n'); return null; }, }); }, specPattern: "./cypress/e2e/features/*.feature", // chromeWebSecurity: false, // 移除或注释此行 experimentalSessionAndOrigin: true, defaultCommandTimeout: 15000, // 其余配置保持不变... }, });
2. 升级并配置正确的Cucumber预处理器
先安装最新版的适配预处理器及打包工具:
npm install @badeball/cypress-cucumber-preprocessor @bahmutov/cypress-esbuild-preprocessor --save-dev
然后更新cypress.config.js中的setupNodeEvents逻辑:
const { defineConfig } = require("cypress"); const createBundler = require("@bahmutov/cypress-esbuild-preprocessor"); const preprocessor = require("@badeball/cypress-cucumber-preprocessor"); const createEsbuildPlugin = require("@badeball/cypress-cucumber-preprocessor/esbuild"); module.exports = defineConfig({ projectId: "t7unhv", e2e: { async setupNodeEvents(on, config) { await preprocessor.addCucumberPreprocessorPlugin(on, config); on( "file:preprocessor", createBundler({ plugins: [createEsbuildPlugin(config)], }) ); on('task', { log(message) { console.log(message +'\n\n'); return null; }, }); return config; }, specPattern: "./cypress/e2e/features/*.feature", experimentalSessionAndOrigin: true, // 其余配置保持不变... }, });
3. 调整测试代码的回调函数类型
将Cucumber步骤的普通function改为箭头函数,避免上下文绑定冲突:
Given(/^the user login to the Test Page$/, () => { cy.visit("https://example-originalURL"); cy.get("button").contains("Login").click(); const credentials = { username: "hello", password: "user", }; cy.origin("https://example-newURL", { args: credentials }, ({ username, password }) => { cy.get("#email", { timeout: 20000 }).type(username); cy.get("#password").type(password, { log: false }); cy.get("button").contains("Login").click(); }); });
4. 基础配置验证
- 确保Cypress版本在12.x以上(
experimentalSessionAndOrigin在12+版本已稳定,无需实验标记) - 确认
cy.origin的目标域名https://example-newURL是登录跳转后的正确域名,无拼写错误
内容的提问来源于stack exchange,提问作者sumitsingh13
相关产品推荐
相关产品推荐

