2015-03-30 27 views
1

我想测试的代码是:如何构建涉及承诺和第三方NPM模块的摩卡咖啡单元测试?

exports.hasTokenOrApi = (req, res, next) -> 
    if not req.headers?.authorization 
    return res.status(403).end() 

    new Promise (resolve, reject) -> 
    if req.headers.authorization.length is 32 
     # We are using an API key 
     global.db.User.find 
     where: 
      api_key: req.headers.authorization 
     .then (dbUser) -> 
     resolve dbUser.apiDisplay() 
    else 
     # We are using a redis session 
     req.redisSession.getAsync 
     app: 'sessions' 
     token: req.headers.authorization 
     .then (response) -> 
     resolve response.d 
    .then (user) -> 
    if not user.id 
     return res.status(403).end() 
    req.user = user 

    next() 
    .catch (err) -> 
    next err 

这是一个中间件(我使用快递)来捕捉各种API端点令牌或API密钥。

到目前为止,我有测试是:

describe 'Authentication Middleware', -> 
    mock_res = {} 
    before (done) -> 
    mock_res = 
     status: -> 
     @ 
     end: -> 
     @ 

    global.db = 
     User: 
     find: -> 
      @ 
     then: -> 
      id: 1 


    done() 

    it 'should return a 403 is no authorization is set in the header', -> 
    mock_req = {} 
    mock_next = null 

    status_spy = sinon.spy mock_res, 'status' 
    end_spy = sinon.spy mock_res, 'end' 

    authentication.hasTokenOrApi mock_req, mock_res, mock_next 
    status_spy.calledWith(403).should.equal true 
    end_spy.called.should.equal true 

    it.only 'should detect a valid API key', -> 
    mock_req = 
     headers: 
     authorization: 'e16b2ab8d12314bf4efbd6203906ea6c' 
    mock_next = sinon.spy() 

    authentication.hasTokenOrApi mock_req, mock_res, mock_next 
    mock_next.called.should.equal true 

的第一个测试是好的,伟大工程,解决了我所有的问题。 第二个工作不正常。我认为这与诺言有关?我测试我们返回false,当我想要做的是true

任何帮助将非常感激!

回答

1

调用next将被异步调用。在它有机会被调用之前,您的测试正在检查mock_next.called。您可以验证next回拨是通过编写自己的回调调用的:

authentication.hasTokenOrApi mock_req, mock_res, err -> 
    if err 
     done err 
    # if the code has entered this callback, and there's no error 
    # that means that the promise has resolved and everything's good... 
    # we can end the test now 
    done() 
2

我只是做:

it.only 'should detect a valid API key', (done) -> 
    mock_req = 
     headers: 
     authorization: 'e16b2ab8d12314bf4efbd6203906ea6c' 

    authentication.hasTokenOrApi mock_req, mock_res, done 

如果done完全没有叫,测试就会超时。如果它被错误调用,那么Mocha会报告错误。

+0

但是不应该在res上存在间谍? – Shamoon 2015-03-31 01:36:35

+0

也许在你的问题中的第二个测试显示'res'没有间谍。无论如何,传递给'hasTokenOrApi'的回调不是立即调用完成,而是可以在'res'模拟器上执行测试,然后调用'done'。 – Louis 2015-03-31 10:28:13

+0

这并不能解决蓝鸟承诺的问题 – Shamoon 2015-04-02 13:24:07