2015-06-24 51 views
0

我有一個處理程序ExpressJS:如何嘲笑請求處理器下一功能與摩卡

public ensureAuthenticated(req: express.Request, res: express.Response, next: Function) { 
    // check header or url parameters or post parameters for token 
     var token = req.body.token || req.param('token') || req.headers['x-access-token']; 
    // decode token 
    if (token) { 
     // verifies secret and checks exp 
     jwt.verify(token, config.secret, function(err, decoded) { 
      if (err) { 
       return res.status(404).json({ success: false, message: 'Failed to authenticate token.' });  
      } else { 
       // if everything is good, save to request for use in other routes 
       next(); 
      } 
     }); 

    } else { 
     // if there is no token 
     // return an error 
     return res.status(403).send({ 
      success: false, 
      message: 'No token provided.' 
     }); 
    } 
    } 

而且這裏的路線

app.post('/api/article/create', AuthenticationHelper.ensureAuthenticated, this.create); 

在單元測試中,我怎麼能嘲笑ensureAuthenticated使確定它已通過身份驗證。

sinon.stub(AuthenticationHelper, 'ensureAuthenticated').returns(true); 

回答

0

我給你舉個例子,我測試它,而無需使用興農。

這是我的認證helper.js:

'use strict'; 

module.exports = function(jwt, config) { 
    return { 
    ensureAuthenticated: function (req, res, next) { 
     var token = req.body.token || 
       req.param('token') || 
       req.headers['x-access-token']; 

     if (token) { 
     jwt.verify(
       token, 
       config.secret, 
       function(err, decoded) { 
       if (err) { 
        res 
        .status(404) 
        .json({ 
        success: false, 
        message: 'Failed to auth.' 
        }); 
       } else { 
        next(); 
       } 
       } 
     ); 
     } else { 
     res 
     .status(403) 
     .send({ 
      success: false, 
      message: 'No token provided.' 
     }); 
     } 
    } 
    }; 
} 

這是我的測試文件:

'use strict'; 

var jwt = {}; 
jwt.verify = function (token, secret, fn) { 
    fn(null, 'something'); 
}; 

var config = {}; 
config.secret = 'shh'; 

var req = {}; 
req.body = {}; 
req.body.token = 'mytoken'; 

var res = {}; 

var AuthenticationHelper = require('./authentication-helper.js')(jwt, config); 

describe('Test Express Middleware', function() { 
    it('should call next on middlware', function(done) { 
    var next = function() { 
     console.log('next was called'); 
     done(); 
    }; 

    AuthenticationHelper.ensureAuthenticated(req, res, next); 
    }); 
});