在 Cypress 中剔除 Angular 服务

rd3*_*415 12 typescript amazon-cognito angular cypress

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

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

在 Angular 我有

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

  isSignedIn(): Observable<boolean> {
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

我想存根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));
  }
}
Run Code Online (Sandbox Code Playgroud)

Cypress/Chrome 然后抱怨它无法在该位置找到 AuthenticationService。我该如何解决这个问题。

The*_*bio 3

您的测试存在一些问题

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

2 - AuthenticationServicecypress 测试中的类与 Angular 使用的类不同...原因有两个:

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

3 - 即使与AuthenticationServiceAngular 的范围相同,它仍然是不正确的......您需要的是来自 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
      })
});

Run Code Online (Sandbox Code Playgroud)

我们可以从角度范围内到浏览器窗口提供对服务的引用。例如,像这样使用你的 AppComponent

export class AppComponent {
  constructor(..., authenticationService: AuthenticationService) {
    window['authenticationService'] = authenticationService;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Run Code Online (Sandbox Code Playgroud)

希望这能让你开始