如何在Cypress自定义命令中正确使用cy.origin传递参数?
问题描述
我尝试编写包含cy.origin的Cypress自定义login命令:
Cypress.Commands.add('login', (userId, password) => { cy.origin('https://some-sso.page', () => { cy.get('input[placeholder="UserID"]').type(userId); cy.get('input[placeholder="Password"]').type(password0); cy.contains('SIGN IN').click(); }); });
调用命令时使用:
cy.login('someUser', '12345');
但出现报错:
userId is not defined Variables must either be defined within the cy.origin() command or passed in using the args option.
我曾在cy.origin内部直接定义常量实现了登录功能,但希望做成可传参的自定义命令,请问该如何实现?
内部定义常量的可行代码:
cy.origin('https://some-sso.page', () => { const userId = 'someUser'; const pass = '12345'; cy.get('input[placeholder="User ID"]').type(userId); cy.get('input[placeholder="Password"]').type(pass); cy.contains('SIGN IN').click(); }); cy.get('#div > section').contains('It works');
解决方案
因为cy.origin的回调函数运行在独立的上下文环境中,无法直接访问外部作用域的变量,必须通过args选项传递参数。修改后的自定义命令如下:
Cypress.Commands.add('login', (userId, password) => { // 通过args选项传递外部变量到cy.origin的回调上下文 cy.origin('https://some-sso.page', { args: { userId, password } }, ({ userId, password }) => { cy.get('input[placeholder="UserID"]').type(userId); cy.get('input[placeholder="Password"]').type(password); // 修正原代码中的password0拼写错误 cy.contains('SIGN IN').click(); }); });
调用方式保持不变:
cy.login('someUser', '12345');
关键说明
- 在
cy.origin的第二个参数位置添加{ args: { userId, password } },将需要传递的变量打包为对象传入 - 回调函数通过参数接收传入的对象,解构出
userId和password后即可在内部使用 - 原代码中的
password0是拼写错误,需修正为password才能正常使用传入的密码参数
内容的提问来源于stack exchange,提问作者pmiranda
相关产品推荐
相关产品推荐

