【发布时间】:2014-08-07 11:55:21
【问题描述】:
我有以下代码,我正在尝试编写使用 mocha 的单元测试。在某些情况下,这按预期工作,但在其他情况下,承诺似乎永远不会解决。你能帮我解决这个问题吗?
被测代码:
exports.inGroup = (group, user) ->
return user.groups.indexOf(group) >= 0
##
# A promise returning function that returns the list
# of viewable channels for a user.
##
exports.getUserViewableChannels = (user) ->
# if admin allow all channels
if exports.inGroup 'admin', user
return Channel.find({}).exec()
else
# otherwise figure out what this user can view
return Channel.find({ txViewAcl: { $in: user.groups } }).exec()
现在,当我测试非管理员用户时,它可以正常工作:
user = new User
firstname: 'Some'
surname: 'User'
email: 'some@user.net'
groups: [ 'HISP' , 'group2' ]
it "should return channels that a user can view", (done) ->
promise = authorisation.getUserViewableChannels user
promise.then (channels) ->
channels.should.have.length(2)
done()
, (err) ->
done err
但是,当我测试管理员用户时,promise 没有解决:
user3 = new User
firstname: 'Random'
surname: 'User'
email: 'someguy@meh.net'
groups: [ 'admin' ]
it "should return all channels for viewing if a user is in the admin group", (done) ->
promise = authorisation.getUserViewableChannels user3
promise.then (channels) ->
channels.should.have.length(3)
done()
, (err) ->
done err
在这种情况下,摩卡测试超时:
Error: timeout of 2000ms exceeded
【问题讨论】:
-
只是一个随机提示:Mocha 在最近的版本中支持开箱即用的 Promise,您可以只返回 Promise,测试将根据其是否履行/拒绝分别通过或失败。
-
哦,太棒了!谢谢,我不知道。
标签: javascript coffeescript mongoose promise mocha.js