Search code examples
unit-testingpromisekarma-jasminebluebirdflush

Flushing all resolved promises in Bluebird


So I'm a new convert to Bluebird from angular and I'm trying to build unit tests for code that uses Bluebird promises. The code I want to test looks like this:

user {
    handleAuth(token) {
        console.log(token);
    },
    login(username, password, saveUsername) {
        return lib.login(username, password).then(this.handleAuth.bind(this));
    },
}

I've mocked out lib.login which returns a promise to instead return a resolved value like this

lib.login.and.returnValue(Promise.resolve(true));

But the handler is not executed in the space of the unit test. In the Angular world, I would need to tell the $timeout service to flush and all the resolved promises would execute their chained methods. What's the equivalent in Bluebird?


Solution

  • You would Promise.setScheduler to control the scheduling:

    const queue = new class CallbackQueue {
      constructor() { this._queue = []; }
      flush() { this._queue.forEach(fn => fn()); }
      push(fn) { this._queue.push(fn); }
    }
    
    Promise.setScheduler(fn => queue.push(fn);
    
    // later
    queue.flush(); // call every callback in a `then`.
    

    Note that you might need to call .flush more than once as more promises are creates in the queue from further thens.

    Note that this is not Promises/A+ compliant. I recommend just writing an async test.