使用间谍与单元测试(sinon.js& buster.js)

时间:2013-04-02 18:41:12

标签: node.js unit-testing sinon buster.js

我第一次尝试使用buster.js来测试sinon.js,我正在尝试使用间谍来测试回调。

我的测试失败了,我猜测assert.calledOnceWith使用'==='来比较预期与实际。

(coffeescript中的所有内容) 这是我的测试用例:

buster      = require 'buster'
_           = require 'underscore'
routeParrot = require '../server/components/routeParrot'

buster.testCase 'routeParrot module',

  setUp: (done) ->

    this.socketioRequest =
      method: 'get'
      url: '/api/users'
      headers: []

    this.httpRequest =
      method: 'get'
      url: '/api/users'
      headers: []

    done()
#  tearDown: (done) ->
#    done()

  'modifies http request to API': () ->

    spy = this.spy()
    routeParrot.http this.httpRequest, {}, (()->), spy

    buster.assert.calledOnceWith spy,
      _.extend(this.httpRequest, requestType: 'http'),
      {jsonAPIRespond: (()->)},
      ->

这是我的错误:

[assert.calledOnceWith] Expected function spy() {} to be called once with arguments { headers: [], method: "get", requestType: "http", url: "/api/users" }, { jsonAPIRespond: function () {} }, function () {}
    spy({ headers: [], method: "get", requestType: "http", url: "/api/users" }, { jsonAPIRespond: function () {} }, function () {})

这里的参考是我的routeParrot模块:

module.exports.http = (req, res, next, router) ->
  req.requestType = 'http'

  if req.url.indexOf '/api' is 0
    #api auth
    #TODO
    res.jsonAPIRespond = (json) ->
      res.json json

    router(req, res, next)
  else
    router(req, res, next)




module.exports.socketio = (req, res, router) ->
  req.requestType = 'socketio'

  httpEmulatedRequest =
    method:   if req.data.method then req.data.method else 'get'
    url:      GLOBAL.apiSubDir + (if req.data.url then req.data.url else '/')
    headers:  []

  response =
    jsonAPIRespond: (json) ->
      req.io.respond json

  #TODO api auth
  router req, res, ->

正如您所看到的,我正在尝试使用嵌入式函数对对象文字进行比较。我是否会离开这里,或者我必须做一些事情,例如覆盖在calledOnceWith中完成的比较?谢谢!

1 个答案:

答案 0 :(得分:1)

问题是您尝试比较功能不同的功能。因此,您在断言中创建的空函数与您的间谍调用的函数不同。

另外,为了提高测试失败的可读性,您应该拆分断言,以便使用单个断言测试每个参数。否则很难发现哪个参数是错误的。

相关问题