Mock Websocket Subject in Angular tests

Viewed 65

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.

1 Answers

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.

Related