小编Geo*_*ell的帖子

等待sinon残缺的承诺解决,然后再对sinon间谍进行断言

我有一个中间件功能,该功能检查会话令牌以查看用户是否为管理员用户。如果所有检查均通过,该函数将不返回任何内容,而仅调用next()。

我如何等待内部异步Promise(adminPromise)解析,然后再对Sinon间谍的next()回调进行断言?当前测试将失败,因为测试中的断言是在AdminMiddleware.prototype.run中的承诺解析之前进行的。

该函数是:

AdminMiddleware.prototype.run = function (req, res, next) {
  let token        = req.header(sessionTokenHeader);
  let adminPromise = new admin().send()

  adminPromise.then(function (authResponse) {
    let adminBoolean = JSON.parse(authResponse).payload.admin;

    if (adminBoolean !== true) {
      return new responseTypes().clientError(res, {
          'user': 'validation.admin'
      }, 403);
    };

    next();
  });
};
Run Code Online (Sandbox Code Playgroud)

和测试:

it('should call next once if admin', function (done) {
    stub = sinon.stub(admin.prototype, 'send');
    stub.resolves(JSON.stringify({success : true, payload : {admin : true}}));
    let nextSpy = sinon.spy();

    AdminMiddleware.prototype.run({header: function () {}}, {}, nextSpy);
    expect(nextSpy.calledOnce).to.be.true;
    done();
});
Run Code Online (Sandbox Code Playgroud)

目前,我正在包装如下所示的期望,这将导致测试通过,但看起来像是hack。此外,如果失败,由于未调用done(),将导致未处理的承诺拒绝错误和超时。

    it('should …
Run Code Online (Sandbox Code Playgroud)

javascript mocha.js sinon sinon-chai

5
推荐指数
1
解决办法
2439
查看次数

标签 统计

javascript ×1

mocha.js ×1

sinon ×1

sinon-chai ×1