title: How to mock rxjs/Websocket in angular for Unit Testing
body: <p>I created a service which handles websocket communication with a server and Im trying to create unit tests for it but I cant find a way to mock <a href="https://rxjs-dev.firebaseapp.com/api/webSocket/webSocket" rel="nofollow noreferrer">rxjs/Websocket</a>.</p>
  
  <p>I found a similar question <a href="https://stackoverflow.com/questions/48584094/how-to-mock-rxjs-observable-websocket-for-unit-tests">here</a>, but I cant use it with the new version of rxjs. Any help will be very helpful. </p>
  
  <p>I could also, inject WebSocket as a service and mock the service in my test but it seems like a workaround and I prefer a better solution </p>
  
  <p>Here is mi code: </p>
  
  <p><code>socket.service.ts</code></p>
  
  <pre class="lang-js prettyprint-override"><code>//imports 
  
  @Injectable()
  export class SocketService {
    private baseUrl = ENV.WS_WORKSPACES_URL;
  
    socket$: WebSocketSubject&lt;any&gt;;
  
    constructor(
      private userService: UserService
    ) { }
  
    initSocket(): void {
      this.socket$ = webSocket(`${this.baseUrl}clusters`);
      const user = this.userService.getUser();
  
      if (user) {
        this.send({token: user.token});
      }
    }
  
    send(data: any): void {
      this.socket$.next(data);
    }
  }
  </code></pre>
  
  <p><code>socket.service.spec.ts</code></p>
  
  <pre class="lang-js prettyprint-override"><code>//imports
  
  describe("SocketService", () =&gt; {
    let service: SocketService;
    let userServiceSpy;
    let socket;
    const token = "whatever";
  
    beforeEach(() =&gt; {
      userServiceSpy = jasmine.createSpyObj("UserService", ["getUser"]);
      userServiceSpy.getUser.and.returnValue(null);
      socket = {next: jasmine.createSpy()};
      TestBed.configureTestingModule({
        providers: [
          {provide: UserService, useValue: userServiceSpy},
          SocketService
        ]
      });
  
      service = TestBed.inject(SocketService);
  
      socket = {} //this should be my mock
    });
  
    it("should be created", () =&gt; {
      expect(service).toBeTruthy();
    });
  
    it("should open connection", () =&gt; {
      service.initSocket();
  
      expect(socket.next).not.toHaveBeenCalled();
      expect(service.socket$).toBeDefined();
    });
  
    it("should open connection with auth", () =&gt; {
      const user = {token};
      userServiceSpy.getUser.and.returnValue(user);
  
      service.initSocket();
      expect(socket.next).toHaveBeenCalledWith(user);
    });
  
    it("should send a message", () =&gt; {
      service.initSocket();
  
      const message = {};
      service.send(message);
  
      expect(socket.next).toHaveBeenCalledWith(message);
    });
  });
  </code></pre>