How to test a function which calls async function using Jasmine

Viewed 6916

How to test this function:

var self = this;
self.someVariable = "initial value";
self.test = function() {
   self.functionWhichReturnsPromise().then(function() {
     self.someVariable = "new value";
   });
}

I have test case like below, I know it is wrong because before promise is resolved, the assert statement will be executed by jasmine:

it("should test the function test", function (done) {
    var abc = new ABC();
    abc.test();
    expect(abc.someVariable).toBe('new value');
});

Note that I do not want to use setTimeout() or any sleep methods.

4 Answers

I've written two samples to show how to wait for the promise inside the test function.
JavaScript: https://codepen.io/zhangyanwei/pen/rNNXKaV

function trackPromise() {
  const P = Promise;
  Promise = function() {
    const p = new P(...arguments);
    Object.assign(this, p);
    Promise.recent = p;
  };
  Object.assign(Promise, P);
}

TypeScript: https://codepen.io/zhangyanwei/pen/ZEEgNNB

// Mixin interface, you could put it into *.d.ts file.
interface PromiseConstructor {
    recent: Promise<unknown>;
}

function trackPromise() {
  // Only overwrite the constructor
  const P = Promise;
  Promise = function<T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T> {
      const p = new P(executor);
      Promise.recent = p;
      return p;
  } as unknown as PromiseConstructor;
}
Related