在 cypress orgin 命令中调用方法时出错

问题描述 投票:0回答:1

我在尝试将登录过程自动化到页面对象中时遇到以下错误。

this.signIn is not a function

这是我的页面对象:

export class OktaLoginPage {
  oktaServer = Cypress.env('oktaServer'); 

  get oktaServer() {
    return this.oktaServer;
  }

  set oktaServer(server) {
    this.oktaServer = server;
  }

  login(username, password) {
    const loginArgs = {username: username, password: password};
    if (this.domainsMatch(this.oktaServer)) {
      this.signIn(username, password);
    } else {
      cy.origin(this.oktaServer, {args: loginArgs}, ({username, password}) => {
        this.signIn(username, password);
      })
    }
  }

  signIn(username, password) {
    cy.contains('h2', 'Sign In');
    cy.get('input[name="username"]').clear();
    cy.get('input[name="username"]').type(username);
    cy.get('input[type="submit"]').invoke('attr', 'value').then(btnValue => {
      if (btnValue === 'Next') {
        cy.get('input[type="submit"]').click();
      }
    });
    cy.get('input[type="password"]').clear().type(password);
    cy.get('input[type="submit"]').click();
  }

    // domainsMatch not shown
}

如果我将signIn方法中的代码复制到cy.orgin块中,它就可以正常工作。在原始块内进行类方法调用存在一些问题。 cypress 文档表明我必须在原始块中定义类/对象。我尝试了几种不同的方法来使其发挥作用,包括:

const OktaLoginPage = Cypress.require('../../support/page-objects/oktaLogin.po');
const login = new OktaLoginPage();
login.signIn(username, password);

需要一些帮助。谢谢。

javascript cypress pageobjects
1个回答
0
投票

错误来自这部分代码

cy.origin(this.oktaServer, {args: loginArgs}, ({username, password}) => {

  // cannot access closure variables here, including "this"
  this.signIn(username, password);
})

这是

cy.origin()
命令的限制。请参阅来源 - 参数

的文档

args 对象是可以将数据注入到回调中的唯一机制,回调不是闭包,并且不保留对其声明所在的 JavaScript 上下文的访问权限。传递到 args 的值必须是可序列化的。


在 cy.origin() 中共享代码

它与页面对象格式不太兼容,但您可以使用

Cypress.require()
来共享代码。

示例共享代码 - 自定义命令展示了如何操作。

cypress/support/commands.js

Cypress.Commands.add('signIn', (username, password) => {
    cy.contains('h2', 'Sign In');
    cy.get('input[name="username"]').clear();
    cy.get('input[name="username"]').type(username);
    cy.get('input[type="submit"]').invoke('attr', 'value').then(btnValue => {
      if (btnValue === 'Next') {
        cy.get('input[type="submit"]').click();
      }
    });
    cy.get('input[type="password"]').clear().type(password);
    cy.get('input[type="submit"]').click();
})

测试

before(() => {
  const oktaDomain =  Cypress.env('oktaServer')
  cy.origin(oktaDomain, () => {
    Cypress.require('../support/commands')  // commands to be used inside okta domain
  })
})

it('testing...', () => {

页面对象

  login(username, password) {
    const loginArgs = {username: username, password: password};
    if (this.domainsMatch(this.oktaServer)) {
      cy.signIn(username, password);
    } else {
      cy.origin(this.oktaServer, {args: loginArgs}, ({username, password}) => {
        cy.signIn(username, password);
      })
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.