3

我有一个要测试的身份验证中间件,该中间件对身份验证服务进行外部调用,并根据返回的 statusCode 调用下一个中间件/控制器或返回一个401状态。像我下面的东西。

var auth = function (req, res, next) {
  needle.get('http://route-auth-service.com', options, function (err, reply) {
      if (reply.statusCode === 200) {
         next();
      } else {
        res.statusCode(401)
      }
  })
}

我使用SinonJS,nocknode-mocks-http进行测试,我的简单测试如下。

 // require all the packages and auth middleware
 it('should login user, function (done) {
   res = httpMocks.createResponse();
   req = httpMocks.createRequest({
     url: '/api',
     cookies: {
       'session': true
     }
   });

   nock('http://route-auth-service.com')
     .get('/')
     .reply(200);

   var next = sinon.spy()
   auth(res, req, next);
   next.called.should.equal(true); // Fails returns false instead
   done();
});

测试总是失败返回false,感觉是因为needle调用是异步的,在调用返回之前就到了assertion部分。我整天都在做这个,我需要帮助。

4

1 回答 1

2

您需要将测试设置与断言分开

// this may be "beforeEach"
// depends on what testing framework you're using
before(function(done){
  res = httpMocks.createResponse();
  req = httpMocks.createRequest({
    url: '/api',
    cookies: {
      'session': true
    }
  });

  nock('http://route-auth-service.com').get('/').reply(200);

  var next = sinon.spy();

  auth(res, req, function() {
    next();
    done();
  });
});

it('should login user', function () {
   next.called.should.equal(true); // Fails returns false instead
});
于 2016-06-30T15:36:21.017 回答