在Bluebird中刷新所有已解决的承诺

问题描述 投票:1回答:1

所以我是从角度转换为Bluebird的新转换器,我正在尝试为使用Bluebird承诺的代码构建单元测试。我想测试的代码如下所示:

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

我已经嘲笑了lib.login,它返回一个promise,而不是像这样返回一个已解析的值

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

但是处理程序不在单元测试的空间中执行。在Angular世界中,我需要告诉$ timeout服务刷新,所有已解析的promise将执行其链式方法。 Bluebird中的等价物是什么?

unit-testing promise karma-jasmine bluebird flush
1个回答
1
投票

你会Promise.setScheduler来控制日程安排:

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`.

请注意,您可能需要多次调用.flush,因为更多的承诺是从更进一步的thens队列中创建的。

请注意,这不符合Promises / A +。我建议只写一个异步测试。

© www.soinside.com 2019 - 2024. All rights reserved.