【问题标题】:How can I test code inside an Angular subscribe block without values being overwritten in subsequent subscribe blocks?如何在 Angular 订阅块中测试代码,而不会在后续订阅块中覆盖值?
【发布时间】:2021-04-08 22:12:13
【问题描述】:

我在 Angular 应用程序中使用 ngx-socket-io,并且我有一个组件,其中包含 ngOnInit() 内的各种 .subscribe 块,随后将在从服务器接收到数据时运行

我的问题是,当我在测试套件中调用 ngOnInit() 时,我无法测试组件变量是否设置为某个特定订阅块内的某个值,因为它将在另一个订阅块内被覆盖。

例如:

组件:

  ngOnInit(): void {
    this.setupBroadcastSubscriptions();
  }

  public setupBroadcastSubscriptions() {
    this.joinGameService.isHost()
      .subscribe((data: any) => {
         this.hostName = data.hostName;
      });
    this.gameService.onUserDisconnection()
      .subscribe((data: any) => {
        this.toastr.info(data.message);
        this.playersInLobby = data.players;
        this.hostName = data.players.find(player => player.isHost).username;
      });
}

测试:

  test('when the first user enters a lobby, it should set the hostName to the user emitted from the server', () => {
    component.ngOnInit();
    expect(component.hostName).toEqual('james');
  });

(为简洁起见,省略了测试套件中的模拟)

我想测试hostName 在isHost 订阅中具体发生了什么。但是,hostName 将在 onUserDisconnection 订阅中被覆盖。

对此的一种解决方案是在订阅块内创建一个方法并单独测试该方法,但我不想测试私有方法。

最好的方法是什么?

【问题讨论】:

标签: angular testing jestjs ngx-socket-io


【解决方案1】:

如果你使用 waitForAsync,你可以使用 tick() 来增加计时器,这样你就可以测试第一个订阅,然后再次打勾并测试第二个订阅。

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 2019-06-21
    • 2019-07-10
    • 2012-10-12
    • 2020-06-25
    相关资源
    最近更新 更多