【问题标题】:Stubbing out Angular services in Cypress在 Cypress 中剔除 Angular 服务
【发布时间】:2020-02-03 14:36:46
【问题描述】:

我有这个 Angular Web 应用程序,我想在模拟的 REST API 上运行 e2e 测试。我可以很容易地将我的网络请求存根到我的 REST API,但身份验证是使用第三方提供商(Cognito 使用 Amplify)。

现在我想删除包装身份验证的 Angular 服务。

在 Angular 我有

@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {
  some methods

  isSignedIn(): Observable<boolean> {
    ...
  }
}

我想存根isSignedIn()-方法。我的第一次尝试看起来像这样:

import {AuthenticationService} from "../../src/app/authentication.service";
import {BehaviorSubject} from "rxjs";

context('albums', () => {

  it('get albums', () => {
    cy.stub(AuthenticationService,'isSignedIn').returns(new BehaviorSubject(true));
  }
}

Cypress/Chrome 然后抱怨它在该位置找不到 AuthenticationService。我该如何解决?

【问题讨论】:

  • 你找到更多关于这方面的信息了吗?
  • 以防其他人在看这个。使用 rxjs of 运算符尝试 of(true) - BehaviourSubject 是类 BehaviourSubject 的实例,而不是 Observable

标签: angular typescript automated-tests cypress amazon-cognito


【解决方案1】:

您的测试存在一些问题

1 - 赛普拉斯本身不在浏览器中执行,它是一个命令浏览器的包装应用程序。它使用 JS 语言,但在包装器上不与浏览器一起使用。它可以向浏览器发送 JS 命令,我将在下面解释。

2 - 您的 cypress 测试中的 AuthenticationService 类与 angular 使用的类不同...有两个原因:

  • 当我们将一个类导入 Cypress 测试时,Cypress 将使用它的预处理器从 ts 文件中构建一个新的 js 类;此类将是与使用其预处理器创建的一个 Angular 不同的对象。
  • 测试中的类导入将在 cypress 范围内加载(不是浏览器加载 angular 的范围)

3 - 即使AuthenticationService 与 Angular 的范围相同,它仍然是不正确的......您需要的是 Angular 范围/区域内的此类实例。

不用担心,Cypress 允许您通过其Window 函数进入浏览器的范围:

cy.window()
      .then((window) => { // the window here is the browser's
        window['console'].log('Hi there from Cypress scope'); // this will appear in the console window within cypress
      })
});

我们可以在 Angular 的范围内向浏览器窗口提供对服务的引用。例如,像这样使用您的 AppComponent

export class AppComponent {
  constructor(..., authenticationService: AuthenticationService) {
    window['authenticationService'] = authenticationService;
  }
}

并使用 cypress 的 Window 函数获取浏览器的 window 对象,然后您的测试可以存根该服务:

cy.window().then((window) => {
  const serviceFromAngularScope = window['authenticationService'];

  cy.stub(serviceFromAngularScope,'isSignedIn').returns(new BehaviorSubject(true));
});

希望这能让你开始

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-25
    • 2019-11-21
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 2014-09-22
    • 2017-12-16
    相关资源
    最近更新 更多