Unit testing 我如何构建一个包含承诺和第三方NPM模块的摩卡单元测试?

Unit testing 我如何构建一个包含承诺和第三方NPM模块的摩卡单元测试?,unit-testing,coffeescript,promise,mocha.js,sinon,Unit Testing,Coffeescript,Promise,Mocha.js,Sinon,我尝试测试的代码是: 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

我尝试测试的代码是:

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
这是一个中间件(我使用Express)来捕获各种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
第一次测试很好,效果很好,解决了我所有的问题。 第二个不能正常工作。我想这和承诺有关吧?当我试图做的是
true
时,我的测试将返回
false

任何帮助都将不胜感激

我只想:

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

    authentication.hasTokenOrApi mock_req, mock_res, done

如果根本没有调用
done
,测试将超时。如果调用时出现错误,Mocha将报告错误。

将异步调用回调
next
。您的测试正在下一步检查
mock\u。在有机会调用它之前调用它。您可以通过将自己的回调写入以下内容来验证是否调用了
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()

但是res上不应该有间谍吗?也许你问题中的第二个测试显示
res
没有间谍。无论如何,传递给
hasTokenOrApi
的回调可以在
res
mock上执行测试,然后调用
done
,而不是立即调用done。