【发布时间】:2020-12-15 08:11:02
【问题描述】:
在我的 component.ts 文件中,我有一个名为“socketService”的服务,我在其中使用套接字,在组件中,我有一行
this.socket = this.socketService.getSocketIOConnector(this.data.product)
this.socket.on('connected', (message: string) => {
this.connectionMsg = message
})
在我的 spec.ts 文件中,我有
beforeEach(async(() => {
fixture = TestBed.createComponent(OndemandComponent);
component = fixture.componentInstance;
fixture.detectChanges();
}));
it("should check socket service", inject([SocketioService], (socketioService: SocketioService) => {
socketioService = TestBed.get(SocketioService);
const spy = spyOn(socketioService, "getSocketIOConnector");
expect(spy).toHaveBeenCalled();
}));
it("should create", () => {
expect(component).toBeTruthy();
});
它给了我 TypeError: Cannot read property 'on' of undefined while testing near this.socket.on in component.
【问题讨论】:
-
嗨!首先,你能把整个代码吗?您是否定义了 component.data.product 属性?稍后,如果您使用 inject() 方法,则不需要使用 TestBed.get()。它们都应该是同一个实例。所以我建议你只使用一个。另外,您可以使用 TestBed.inject() 方法来代替
socketioService = TestBed.inject(SocketioService);希望它有所帮助。 -
@lorenago 感谢您的指出。那是我的错误,我忘记移除 TetBed。但我仍然遇到同样的错误
-
请告诉我们你是怎么打电话给
TestBed.configureTestingModule(..)的。 -
您在哪里打电话给
this.socket.on、constructor或ngOnInit? -
@slideshowp2 在 ngOnInit 中调用它
标签: angular typescript unit-testing socket.io karma-jasmine