2012-08-09 56 views
3

请考虑,我有以下的CoffeeScript代码:奇怪fs.readFile行为

class Foobar 
    test: (path) -> 
     fs = require 'fs' 
     fs.readFile path, (err, data) -> 
      console.log 'fs.readFile callback fired' 

root = exports ? window 
root.Foobar = Foobar 

而下面的测试文件的摩卡:

chai = require 'chai' 
expect = chai.expect 
chai.should() 

{Foobar} = require '../source/foobar' 

describe 'Foobar', -> 
    foobar = null 
    it 'does nothing', -> 
     foobar = new Foobar 
     foobar.test 'foobar.txt' 

运行测试:

mocha --compilers coffee:coffee-script -R spec 

奇怪的是我的控制台没有记录任何东西。当我改变我的咖啡这(加在最后两行):

class Foobar 
    test: (path) -> 
     fs = require 'fs' 
     fs.readFile path, (err, data) -> 
      console.log 'fs.readFile callback fired' 

root = exports ? window 
root.Foobar = Foobar 

foobar = new Foobar 
foobar.test 'foobar.txt' 

运行测试,现在控制台日志fs.readFile callback fired两次,符合市场预期。

那么,为什么控制台在第一种情况下是空的?

回答

3

在执行readFile回调之前,您的测试有可能会结束。该test方法应该接受回调:

class Foobar 
    test: (path, callback) -> 
     fs.readFile path, (err, data) -> 
      console.log 'fs.readFile callback fired' 
      callback err, data 

这样,你可以写你的测试,以异步运行:

it 'calls callback', (done) -> 
    foobar = new Foobar() 
    foobar.test 'foobar.txt', done