angular - 使用 Angular 服务使用 cypress 登录

标签 angular cypress

我正在使用 cypress 来测试我们的 Angular 应用程序。在阅读了很多关于 cypress 的最佳实践之后,我现在想重构我们的自定义 cypress 登录命令。目前它使用 UI 登录。

我找到了有关如何使用应用程序代码 (https://github.com/cypress-io/cypress-example-recipes/tree/master/examples/logging-in__using-app-code) 登录的示例,但我在使用 Angular 应用程序时遇到了麻烦。显然,我们正在使用 Angular 服务来处理登录。现在尝试从示例中复制代码并不能使用 Angular 服务:

// test.spec
import { AuthService } from 'src/app/core/http/auth.service'

describe('Landing Page Test', () => {
  it('should log the user in running app code', () => {
    // I cannot run it like this, coz service is a class
    AuthService.login('username','password');

    // I also cannot instantiate the AuthService because it has injected dependencies
    // so this does not compile:
    const authService = new AuthService();
  });
});

// AuthService (shortend ...)
@Injectable({
  providedIn: 'root'
})
export class AuthService {
  constructor(private apiHttpService: ApiHttpService) {}

  login(username, password) {
    // do login stuff
  }
}

有什么方法可以利用该服务并从那里运行登录?或者这对 Angular 来说是不可能的吗?

最佳答案

哦,我找到了答案,但它看起来很老套,您将以下内容添加到您的服务中:

constructor() {
    if (window['Cypress']) window['AuthService'] = this
}

myFunctionName() {
    console.log("Oh I hope I'll get called from Cypress!")
}

在 Cypress 中,您将能够做到这一点:

it.only('Dev', () => {
    cy.window().then((w) => {
        w.AuthService.myFunctionName()
    })
})

关于angular - 使用 Angular 服务使用 cypress 登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59750186/

相关文章:

angular - 在 Angular 2 中获取 "Property X is missing in type error"

forms - 类型 'http' 上不存在属性 'Component',Angular 2

Angular 2 形式 "Cannot find control with path"

json - NodeJS 和 HTTP : How to send JSON content in a POST/PUT call as a string rather than creating a new key

node.js - 使用 MEAN 和 Node Mailer 将电子邮件发送到动态发件人地址

javascript - 如何计算 Cypress 断言中的 DOM 元素

Dockerfile - 使用目标的哪个选项?

Cypress 检查元素是否有滚动条可见

cypress - 如何从网页上的元素查询值并将它们配对

reactjs - Cypress - 在继续之前等待下一个按钮重新出现