UserHelper = getTestUser: (callback) -> User.findByUUID "4CD5E71C-EBD3-4E15-8AE3-84570EA340EC", (err, user) -> User.findByUUID "4c003162-00fa-426f-9542-fe2c26b31f1b", (err, staff) -> callback user, staff
describe "App", -> client = null user = null staff = null beforeEach -> server.start client = io.connect socketURL, options UserHelper.getTestUser (userCB,staffCB)-> user = userCB staff = staffCB
afterEach -> server.stop
describe "#hello", -> it "no callback", (done) -> client.once "connect", -> client.emit "hello", appkey: “083a7ccf484b2e49a8e46d80” uuid: user.uuid
为什么user是null呢?
UserHelper.getTestUser是一个异步函数,所以beforeEach的回调函数也要使用异步的形式:
beforeEach (done) ->
server.start
client = io.connect socketURL, options
UserHelper.getTestUser (userCB,staffCB)->
user = userCB
staff = staffCB
done()
另外node.js约定callback形式的异步函数,传给回调函数的第一个参数是error对象,所以你第四行callback user, staff
这样的代码是不符合约定的,当和async之类的类库一起用的时候很容易出问题。