title: Testing promise in Angular 2 ngOnInit
body: <p>I have an Angular 2 component I am trying to put under test, but I am having trouble because the data is set in the <code>ngOnInit</code> function, so is not immediately available in the unit test.</p>
  
  <p>user-view.component.ts:</p>
  
  <pre><code>import {Component, OnInit} from 'angular2/core';
  import {RouteParams} from 'angular2/router';
  
  import {User} from './user';
  import {UserService} from './user.service';
  
  @Component({
    selector: 'user-view',
    templateUrl: './components/users/view.html'
  })
  export class UserViewComponent implements OnInit {
    public user: User;
  
    constructor(
      private _routeParams: RouteParams,
      private _userService: UserService
    ) {}
  
    ngOnInit() {
      const id: number = parseInt(this._routeParams.get('id'));
  
      this._userService
        .getUser(id)
        .then(user =&gt; {
          console.info(user);
          this.user = user;
        });
    }
  }
  </code></pre>
  
  <p>user.service.ts:</p>
  
  <pre><code>import {Injectable} from 'angular2/core';
  
  // mock-users is a static JS array
  import {users} from './mock-users';
  import {User} from './user';
  
  @Injectable()
  export class UserService {
    getUsers() : Promise&lt;User[]&gt; {
      return Promise.resolve(users);
    }
  
    getUser(id: number) : Promise&lt;User&gt; {
      return Promise.resolve(users[id]);
    }
  }
  </code></pre>
  
  <p>user-view.component.spec.ts:</p>
  
  <pre><code>import {
    beforeEachProviders,
    describe,
    expect,
    it,
    injectAsync,
    TestComponentBuilder
  } from 'angular2/testing';
  import {provide} from 'angular2/core';
  import {RouteParams} from 'angular2/router';
  import {DOM} from 'angular2/src/platform/dom/dom_adapter';
  
  import {UserViewComponent} from './user-view.component';
  
  import {UserService} from './user.service';
  
  export function main() {
    describe('User view component', () =&gt; {
      beforeEachProviders(() =&gt; [
        provide(RouteParams, { useValue: new RouteParams({ id: '0' }) }),
        UserService
      ]);
  
      it('should have a name', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) =&gt; {
        return tcb.createAsync(UserViewComponent)
          .then((rootTC) =&gt; {
            spyOn(console, 'info');
  
            let uvDOMEl = rootTC.nativeElement;
            rootTC.detectChanges();
  
            expect(console.info).toHaveBeenCalledWith(0);
            expect(DOM.querySelectorAll(uvDOMEl, 'h2').length).toBe(0);
          });
      }));
  
    });
  }
  </code></pre>
  
  <p>The route param is getting passed correctly, but the view hasn't changed before the tests are run. How do I set up a test that happens after the promise in ngOnInit is resolved?</p>