【发布时间】: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 订阅中被覆盖。
对此的一种解决方案是在订阅块内创建一个方法并单独测试该方法,但我不想测试私有方法。
最好的方法是什么?
【问题讨论】:
-
您说为简洁起见省略了模拟,但它们是其中的关键部分(以及通常的minimal reproducible example 要求)。如果您的模拟方法基于 subjects 返回可观察对象,则您可以准确控制它们是否以及何时发出什么值。看看我在github.com/textbook/salary-stats/blob/…做了什么,例如
标签: angular testing jestjs ngx-socket-io