Testing asynchronous code

The MathDemo class also includes an asynchronous version of the same method:

public powAsync(base: number, exponent: number) { 
  return new Promise<number>((resolve) => { 
    setTimeout( 
      () => { 
        const result = this.pow(base, exponent); 
        resolve(result); 
      }, 
      0 
    ); 
  }); 
} 

If we try to test this method, and we don't wait for its result, our test will be useless. However, if we wait for the result, using the Promise.then method, our test will also fail, unless we pass a callback (named done in the example) function to the test-case handler:

it("Should return the correct numeric value for pow", (done) => { const math = new MathDemo(); math.powAsync(2, 3).then((result: number) => { const expected = 8; expect(result).to.be.a("number"); ...

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.