ジャスミンでファイルアクセスをテストするのに問題があります。私はrequire('fs').watch
でコールバックを登録し、ファイルの名前を含むイベントを出すシンプルなウォッチャーを書いています。jasmineとnode.jsでファイルシステムを偽装する
しかし、私がfs
モジュールをモックするテストを書くとき、いくつかの問題があります。ここで
は私のウォッチャークラス(先の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')
そして、ここで私のテストです:
it 'should check if the file exists', ->
spyOn(path, 'existsSync').andReturn(true)
watcher.watch 'existing_file.js'
expect(path.existsSync).toHaveBeenCalledWith 'existing_file.js'
この1つがうまく機能し、問題なく通るが、この1つは完全に失敗し、私は私が正しく引数を渡しているかどうかはわかりません。
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'
そして最後の1つは私には奇妙なものです([オブジェクト]にはメソッドがありません)。これは間違っています。第二の問題については
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')
は、私はちょうど閉鎖で私の関数呼び出しをラップし、それが働いていたが、私は本当に私のテストを実行するときに、
this
コンテキストが完全に台無しにされた理由を理解する必要があります。
ええ、ありがとう、私は最初の問題を解決する方法を考え出しました。あなたのソリューションはよりシンプルに見え、魅力のように機能します。 –