我正在尝试测试类似的代码
testFind = (cb) ->
cb()
wrapper = (fn) ->
(req, mongodb) ->
users = mongodb.db.collection("user")
# fired here
fn req, mongodb
testFind (err, user) ->
#fired here
fn req, mongodb
users.findOne
"username": "user1"
, (err, user) ->
console.log "user is valid", user
console.log "req.done is still a spy object", req.done
#not fired here
fn req, mongodb
test = wrapper (req, mongodb) ->
req.done 200
module.exports = test
并传递req.done
的间谍。正如上面的评论中提到的,间谍永远不会在mongodb回调中被触发,即使它是一个有效的间谍对象并且调用了回调。但它在它之外工作。如果我用调用回调的本地示例函数替换mongodb findOne,它也可以工作。这是测试代码
mongodb = {}
describe.only "test:", ->
before (done) ->
this.timeout(5000)
MongoClient.connect "mongodb://localhost/test", (err, db) ->
if err?
done err
mongodb.db = db
done()
it "should fire complete", ->
@req =
complete: sinon.spy().named("complete")
test @req, mongodb
@req.complete.should.have.been.calledThrice