【问题标题】:NodeJS: How to test middleware making external callNodeJS:如何测试中间件进行外部调用
【发布时间】:2016-11-02 19:15:12
【问题描述】:

我有一个要测试的身份验证中间件,该中间件对身份验证服务进行外部调用,并根据返回的 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)
      }
  })
}

我使用SinonJSnocknode-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部分。我整天都在做这个,我需要帮助。

【问题讨论】:

    标签: node.js express sinon nock needle.js


    【解决方案1】:

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

    // 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
    });
    

    【讨论】:

    • 谢谢@Derick Bailey,我真的很感激,我发现我学到的关于 SO 的提问比我读过的大多数书都多,它可以按我的意愿工作。
    • 我在测试返回状态码不是 200 时遇到问题,我该怎么做?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-08
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-07
    • 1970-01-01
    相关资源
    最近更新 更多