如何解决如何在 Angular 订阅块中测试代码而不会在后续订阅块中覆盖值?
我在 Angular 应用程序中使用 ngx-socket-io,我有一个组件,其中包含 .subscribe
内的各种 ngOnInit()
块,随后在从服务器接收数据时运行
我的问题是,当我在测试套件中调用 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
订阅内被覆盖。
对此的一种解决方案是在订阅块内创建一个方法并单独测试该方法,但我不想测试私有方法。
最好的方法是什么?
解决方法
如果您使用 waitForAsync,您可以使用 tick() 以这样一种方式增加计时器,您可以测试第一个订阅,然后再次勾选并测试第二个订阅。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。