Angular2 http call make tests execute twice

I have a Angular2 app with a simple component

@Component({
  selector: 'Techs',
  template: '',
  providers: [HTTP_PROVIDERS]
})
export class Techs {
  public techs: Tech[];

  constructor(http: Http) {
    http
      .get('src/app/techs/techs.json')
      .map(response => response.json())
      .subscribe(result => this.techs = result);
  }
}

My tests are executed twice:

Chrome 49.0.2623 (Mac OS X 10.11.4): Executed 0 of 6 SUCCESS (0 secs / 0 secs)

LOG: ‘end of test’

Chrome 49.0.2623 (Mac OS X 10.11.4): Executed 6 of 6 SUCCESS (0.182 secs / 0.153 secs)

However if I remove the Http call the test is only executed once

Chrome 49.0.2623 (Mac OS X 10.11.4): Executed 6 of 6 SUCCESS (0.182 secs / 0.153 secs)

Here is my test

describe('techs component', () => {
  it('should render 3 elements <tech>', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
    return tcb
      .createAsync(Techs)
      .then(fixture => {
        fixture.componentInstance.techs = [{}, {}, {}];
        fixture.detectChanges();
        const techs = fixture.nativeElement;
        expect(techs.querySelectorAll('tech').length).toBe(3);
      });
  }));
});

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

I think that your problem comes from the asynchronous aspect of your HTTP call. I would see two ways to fix this: Another way would be to mock your Http object into order to simulate the HTTP call. This can be done using the MockBackend class. Here is to configure it against the XHRBackend class: beforeEachProviders(() => { return [ HTTP_PROVIDERS, provide(XHRBackend, { useClass: MockBackend }), ]; }); and a way to return what you want in the response: it('Should return a list of dogs', inject([XHRBackend, HttpService, Injector], (mockBackend, httpService, injector) => { mockBackend.connections.subscribe( (connection: MockConnection) => { connection.mockRespond(new Response(… Read more »