Angular2 - Testing ngOninit in Components
<p>I have a listing component with following code:</p>

<pre><code>///&lt;reference path="../../node_modules/angular2/typings/browser.d.ts"/&gt;
import { Component, OnInit } from 'angular2/core';
import { ROUTER_DIRECTIVES } from 'angular2/router';

import { Employee } from '../models/employee';
import { EmployeeListServiceComponent } from '../services/employee-list-service.component';

@Component({
  selector: 'employee-list',
  template: `
    &lt;ul class="employees"&gt;
  &lt;li *ngFor="#employee of employees"&gt;
    &lt;a [routerLink]="['EmployeeDetail', {id: employee.id}]"&gt;
      &lt;span class="badge"&gt;{{employee.id}}&lt;/span&gt;
      {{employee.name}}
    &lt;/a&gt;
  &lt;/li&gt;
&lt;/ul&gt;
  `,
  directives: [ROUTER_DIRECTIVES],
  providers: [EmployeeListServiceComponent]
})

export class EmployeeListComponent implements OnInit {
  public employees: Employee[];
  public errorMessage: string;

  constructor(
    private _listingService: EmployeeListServiceComponent
  ){}

  ngOnInit() {
    this._listingService.getEmployees().subscribe(
                     employees =&gt; this.employees = employees,
                     error =&gt;  this.errorMessage = &lt;any&gt;error
                   );
  }
}
</code></pre>

<p>I wish to write unit tests for the <code>ngOninit</code> hook. I have written following test:</p>

<pre><code>/// &lt;reference path="../../typings/main/ambient/jasmine/jasmine.d.ts" /&gt;

import {
    it,
    describe,
    expect,
    TestComponentBuilder,
    injectAsync,
    setBaseTestProviders,
    beforeEachProviders,
} from "angular2/testing";
import { Component, provide, ApplicationRef, OnInit } from "angular2/core";
import {
    TEST_BROWSER_PLATFORM_PROVIDERS,
    TEST_BROWSER_APPLICATION_PROVIDERS
} from "angular2/platform/testing/browser";
import {
    ROUTER_DIRECTIVES,
    ROUTER_PROVIDERS,
    ROUTER_PRIMARY_COMPONENT,
    APP_BASE_HREF
} from 'angular2/router';
import {XHRBackend, HTTP_PROVIDERS} from "angular2/http";
import { MockApplicationRef } from 'angular2/src/mock/mock_application_ref';
import {MockBackend } from "angular2/src/http/backends/mock_backend";
import {Observable} from 'rxjs/Rx';
import 'rxjs/Rx';

import { Employee } from '../models/employee';
import { EmployeeListComponent } from './list.component';
import { EmployeeListServiceComponent } from '../services/employee-list-service.component';


class MockEmployeeListServiceComponent {

    getEmployees () {
        return Observable.of([
            {
                "id": 1,
                "name": "Abhinav Mishra"
            }
        ]);
    }
}


@Component({
    template: '&lt;employee-list&gt;&lt;/employee-list&gt;',
    directives: [EmployeeListComponent],
    providers: [MockEmployeeListServiceComponent]
})
class TestMyList {}


describe('Employee List Tests', () =&gt; {
    setBaseTestProviders(TEST_BROWSER_PLATFORM_PROVIDERS, TEST_BROWSER_APPLICATION_PROVIDERS);

    beforeEachProviders(() =&gt; {
        return [
            ROUTER_DIRECTIVES,
            ROUTER_PROVIDERS,
            HTTP_PROVIDERS,
            provide(EmployeeListServiceComponent, {useClass: MockEmployeeListServiceComponent}),
            provide(XHRBackend, {useClass: MockBackend}),
            provide(APP_BASE_HREF, {useValue: '/'}),
            provide(ROUTER_PRIMARY_COMPONENT, {useValue: EmployeeListComponent}),
            provide(ApplicationRef, {useClass: MockApplicationRef})
        ]
    });

    it('Should be true',
        injectAsync([TestComponentBuilder], (tcb) =&gt; {
            return tcb
                .createAsync(TestMyList)
                .then((fixture) =&gt; {
                    fixture.detectChanges();
                    var compiled = fixture.debugElement.nativeElement;
                    console.log(compiled.innerHTML);
                    expect(true).toBe(true);
                });
        })
    );
});
</code></pre>

<p>However, the output of <code>console.log</code> in the test is an empty <code>ul</code> tag as follows:</p>

<pre><code> '&lt;employee-list&gt;
    &lt;ul class="employees"&gt;
  &lt;!--template bindings={}--&gt;
&lt;/ul&gt;
  &lt;/employee-list&gt;'
</code></pre>

<p>Can anyone suggest me the proper way of writing unit tests for component hooks?</p>

<p><strong>SOLUTION</strong></p>

<p>Mock the http request in the <code>injectAsync</code> block as follows:</p>

<pre><code>backend.connections.subscribe(
                (connection:MockConnection) =&gt; {
                    var options = new ResponseOptions({
                        body: [
                            {
                                "id": 1,
                                "name": "Abhinav Mishra"
                            }
                        ]
                    });

                    var response = new Response(options);

                    connection.mockRespond(response);
                }
            );
</code></pre>

<p>However now i am getting another error as follows:</p>

<pre><code>Failed: EXCEPTION: Component "EmployeeListComponent" has no route config. in [['EmployeeDetail', {id: employee.id}] in EmployeeListComponent@3:7]
        ORIGINAL EXCEPTION: Component "EmployeeListComponent" has no route config.
        ORIGINAL STACKTRACE:
        Error: Component "EmployeeListComponent" has no route config.
</code></pre>