title: How to establish a websocket connection in Angular unit tests?
body: <p>I'm working on an Angular (v 6.1.0) app which is communicating with a backend over a websocket. So far everything's been working fine except for the unit testing. I've created a mock backend for the purpose of testing my components but I just can't establish a connection between the mock backend and testing modules. I'm using Jasmine as an assertion library and Jest as a test runner, this is a sample test suite:</p>
  
  <pre class="lang-ts prettyprint-override"><code>describe('RandomComponent', () =&gt; {
    let component: RandomComponent;
    let fixture: ComponentFixture&lt;RandomComponent&gt;;
  
    beforeEach(async(() =&gt; {
      TestBed.configureTestingModule({
        declarations: [],
        imports: [SomeModule],
        providers: [SpecialWebSocketService, WebSocketService,
          { provide: BackendUrlService, useClass: BackendUrlMockService }
        ]
      })
        .compileComponents();
    }));
  
    beforeEach(() =&gt; {
      fixture = TestBed.createComponent(RandomComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
    });
  
    it('should create random component', () =&gt; {
        expect(component).toBeTruthy();
    });
  });
  </code></pre>
  
  <p>BackendUrlMockService is there just to provide a URL. The single test case produces the following:</p>
  
  <pre class="lang-bash prettyprint-override"><code> FAIL  src/app/path/to/my/random.component.spec.ts
    RandomComponent
      ✕ should create random component (603ms)
  
    ● RandomComponent › should create random component
  
      InvalidStateError: Still in CONNECTING state.
  </code></pre>
  
  <p>Application works fine both with real backend and the mocked one. Testing modules work with neither. I also noticed that if I add a timeout to the test case:</p>
  
  <pre class="lang-ts prettyprint-override"><code>it('should create random component', (done) =&gt; {
    setTimeout(() =&gt; {
      expect(component).toBeTruthy();
      done();
    }, 1000);
  });
  </code></pre>
  
  <p>My mock backend logs a message that connection was established properly but I still get the error. Does anyone have an idea how to set up everything properly so that I could test my components?</p>