用jasmine和node.js嘲笑文件系统
我在用茉莉花testing我的文件访问时遇到了麻烦。 我正在写一个简单的监视器,用require('fs').watch
注册一个callback函数, require('fs').watch
并发出一个包含文件名称的事件,这里没有什么特别的。
但是,当我尝试编写模拟fs
模块的testing时,我遇到了一些问题。
这是我的Watcher类(CoffeeScript提前)
class Watcher extends EventEmitter constructor: -> @files = [] watch: (filename) -> if !path.existsSync filename throw "File does not exist." @files.push(filename) fs.watchFile filename, (current, previous) -> this.emit('file_changed')
这是我的testing:
it 'should check if the file exists', -> spyOn(path, 'existsSync').andReturn(true) watcher.watch 'existing_file.js' expect(path.existsSync).toHaveBeenCalledWith 'existing_file.js'
这个工作正常,通过没有任何问题,但这个完全失败,我不知道我是否正确传递的论据。
it 'should throw an exception if file doesn\'t exists', -> spyOn(path, 'existsSync').andReturn(false) expect(watcher.watch, 'undefined_file.js').toThrow() expect(path.existsSync).toHaveBeenCalledWith 'undefined_file.js'
而最后一个给我和奇怪的([对象]没有一个方法发射)“这是错误的。
it 'should emit an event when a file changes', -> spyOn(fs, 'watchFile').andCallFake (file, callback) -> setTimeout( -> callback {mtime: 10}, {mtime: 5} , 100) spyOn(path, 'existsSync').andReturn(true) watcher.watch 'existing_file.js' waits 500 expect(watcher.emit).toHaveBeenCalledWith('file_changed')
对于第二个问题,我只是将函数调用封装在一个闭包中,而且工作正常,但是我真的需要理解为什么运行我的testing时, this
上下文是完全混乱的。
看到这个问题
我认为你需要做的是:
expect(-> watcher.watch 'undefined_file.js').toThrow 'File does not exist.'
其中定义了期望匹配器在实际testing运行期间可以调用的匿名函数,而不是在testing定义时间期间。
对于你的第二个问题,你只能在茉莉间谍对象上调用toHaveBeenCalled
,而不是任意的函数。 你可以用function来包装function
spyOn(watcher, 'emit').andCallThrough()
查看Spy.andCallThrough()上的jasmine API文档
你可以使用memfs
进行文件系统memfs
。