Issue
Is there a way to properly mock the websocket subject from Rxjs in Angular?
I have the following service, which is injected in few components:
import {Injectable} from '@angular/core';
import {webSocket} from "rxjs/webSocket";
@Injectable({
providedIn: 'root'
})
export class WebsocketApi {
public websocketSubject = webSocket("ws://localhost:8080");
constructor() {
this.subject.subscribe(
event => { // do stuff with the event }
);
}
}
Is there a way that I can easily mock the subject in my WebsocketApi spec file, or elsewhere?
Thanks.
Solution
You need to inject webSocket
instead of declaring it directly in the class, then you can mock it.
export const WEB_SOCKET = new InjectionToken('WEB_SOCKET');
@NgModule({
providers: [
WebsocketApi,
{
provide: WEB_SOCKET,
useFactory: () => webSocket("ws://localhost:8080"),
},
],
})
export class WebSocketModule {}
@Injectable({
providedIn: 'root'
})
export class WebsocketApi {
constructor(@Inject(WEB_SOCKET) public websocketSubject) {
this.subject.subscribe(
event => { // do stuff with the event }
);
}
}
Now in tests, you can replace WEB_SOCKET
with a mock copy.
Answered By - satanTime
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.