title: Why isn't my async Angular Jasmine unit test working?
body: <p>I'm trying to test an asynchronous component method and I think I'm using the asynchronous testing capabilities of Angular 4 correctly, but it isn't working. My problem is that when I run the test, it <strong>doesn't wait</strong> for the Promise to resolve. It seems like the asynchronous nature of function is causing a timeout to be tripped and the test to be exited prematurely. The test will pass no matter what because all <code>expect()</code> statements inside <code>whenStable()</code> get skipped.</p>
  
  <p>If I omit the <code>async()</code> wrapper function and switch to the Jasmine syntax of passing in a <code>done</code> callback and call it at the end of the <code>whenStable()</code> block,  it works correctly. Can anyone tell me why it doesn't work with the Angular <code>async()</code> wrapper? </p>
  
  <p>My code looks like this:</p>
  
  <pre><code>// my.component.ts
  ngOnInit() {
    this.getResults().then((results) =&gt; {
      this.results = results;
    });
  }
  
  // My asynchronous function, which takes 1.5s to load results
  getResults() {
    let promise = new Promise((resolve) =&gt; {
      setTimeout(() =&gt; {
        resolve('foo');
      }, 1500);
    })
    return promise;
  }
  
  
  // my.component.spec.ts (Angular async version which doesn't work)
  it('should load results', async(() =&gt; {
    spyOn(component, 'getResults').and.returnValue(Promise.resolve('bar'));
    component.ngOnInit();
  
    fixture.whenStable().then(() =&gt; {
      // Everything in here gets skipped when I run the test
      fixture.detectChanges();
      // This should cause the test to fail, but it doesn't because it's not run in time
      expect(true).toBe(false)
    });
  }));
  
  // my.component.spec.ts (Jasmine version that works)
  it('should load results', (done) =&gt; {
    spyOn(component, 'getResults').and.returnValue(Promise.resolve('bar'));
    component.ngOnInit();
  
    fixture.whenStable().then(() =&gt; {
      fixture.detectChanges();
      // This should fail and it does because the test works using Jasmine's "done" callback
      expect(true).toBe(false);
      done();
    });
  });
  </code></pre>