node.js - 使用 jasmine 和 node.js 模拟文件系统

标签 node.js mocking jasmine fs

我在使用 jasmine 测试文件访问时遇到问题。我正在编写一个简单的观察程序,它使用 require('fs').watch 注册一个回调,并发出一个包含文件名的事件,这里没什么花哨的。

但是,当我尝试编写模拟 fs 模块的测试时,我遇到了几个问题。

这是我的 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')

这是我的测试:

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'

最后一个给了我一个奇怪的“([Object]没有发出方法)”,这是错误的。

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 上下文完全困惑了。

最佳答案

参见this question

我认为你需要这样做:

expect(-> watcher.watch 'undefined_file.js').toThrow 'File does not exist.'

它定义了一个匿名函数,期望匹配器可以在实际测试运行期间调用该函数,而不是在测试定义时间期间调用。

对于第二个问题,您只能在 jasmine spy 对象上调用 toHaveBeenCalled ,而不能调用任何任意函数。你可以用doing来包装函数

spyOn(watcher, 'emit').andCallThrough()

参见the jasmine API docs on Spy.andCallThrough()

关于node.js - 使用 jasmine 和 node.js 模拟文件系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6970016/

相关文章:

node.js - mongoDB 子文档匹配,其中 elemMatch 不是对象

javascript - 我如何找到元素 <a> 并单击

Angular 2 测试 : Async callback was not invoked within timeout specified by jasmine. DEFAULT_TIMEOUT_INTERVAL

javascript - Mongoose 无需查询即可获取相关数据

node.js - node-postgres Error 是个什么样的对象?为什么 node 的 console.log 和 JSON.stringify 处理方式不一样?

c# - 比较 Linq 查询中的 byte[]

java - 如何模拟来自第三方库的类的静态调用

jenkins - 倾城:Jenkins 插件无法生成报告

ruby-on-rails - 将 RabbitMQ 与 Ruby 和 Node.js 应用程序一起使用?

php - 使用 PHPUnit 模拟私有(private)方法