Cypress中cy.origin()内调用外部函数失败的解决方案咨询
Cypress中cy.origin()内调用外部函数的解决方案
你的问题核心是cy.origin()会创建独立的执行上下文,外部定义的searchFlight函数默认无法被回调内部访问,这就是报错提示要求变量要么在回调内定义、要么通过args选项传递的原因。
下面是两种可行的解决方法:
方法1:通过args选项传递函数(推荐)
利用cy.origin()的args参数将外部函数传入新上下文,避免代码重复:
const searchFlight = async () => { cy.get('#sel-departure-0').should('be.visible', 'Abreise').type('FRA'); } if (Preprod === url.preprod_url_de) { // 通过args传递searchFlight函数,在回调中解构使用 cy.origin('www.example.com', { args: { searchFlight } }, ({ searchFlight }) => { searchFlight(); }) } else { searchFlight(); }
方法2:在cy.origin()回调内部定义函数
如果不想传递外部函数,可以直接在回调内重新定义函数(缺点是代码重复,仅适合简单逻辑):
if (Preprod === url.preprod_url_de) { cy.origin('www.example.com', () => { const searchFlight = async () => { cy.get('#sel-departure-0').should('be.visible', 'Abreise').type('FRA'); } searchFlight(); }) } else { const searchFlight = async () => { cy.get('#sel-departure-0').should('be.visible', 'Abreise').type('FRA'); } searchFlight(); }
注意事项
- 确保你的Cypress版本支持
args选项(Cypress 10+已支持该特性); - 传递的函数不能包含对外部闭包变量的引用(除非这些变量也通过
args传递),否则会因为序列化失败导致报错。
内容的提问来源于stack exchange,提问作者Ramesh Manglani
相关产品推荐
相关产品推荐

