【问题标题】:Strange fs.readFile behavior while testing CoffeeScript with Mocha/Chai使用 Mocha/Chai 测试 CoffeeScript 时出现奇怪的 fs.readFile 行为
【发布时间】:2012-08-07 06:37:32
【问题描述】:

请考虑我有以下 CoffeeScript 代码:

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

root = exports ? window
root.Foobar = Foobar

Mocha 的测试文件如下:

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

对我来说奇怪的是控制台没有记录任何内容。当我将 Coffee 更改为此(在末尾添加两行)时:

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 两次,正如预期的那样。

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

【问题讨论】:

    标签: node.js coffeescript mocha.js fs chai


    【解决方案1】:

    您的测试可能在 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
    

    【讨论】:

      猜你喜欢
      • 2017-02-18
      • 2017-02-04
      • 2019-02-15
      • 1970-01-01
      • 1970-01-01
      • 2013-04-11
      • 1970-01-01
      • 2020-08-08
      • 2023-03-22
      相关资源
      最近更新 更多