Search code examples
node.jsunit-testingsinonbuster.js

Using spies with unit tests (sinon.js & buster.js)


I'm trying out sinon.js with buster.js for the first time and I'm trying to use spies to test a callback.

My test is failing and I'm guessing assert.calledOnceWith is using '===' to compare expected with actual.

(everything in coffeescript) Here's my test case:

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: (()->)},
      ->

And here's my error:

[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 () {})

And for reference here's my routeParrot module:

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, ->

As you can see I'm trying to do a comparison on object literals with embedded functions. Am I way off base here or do I have to do something like override the comparison done within calledOnceWith? Thanks!


Solution

  • The problem is that you try to compare function different functions. So the empty functions that you create in your assertion cant be the same one that your spy was called with.

    Also for better readability of test failures you should splitt up the assertions so you test every parameter with a single assertion. Otherwise its hard to spot which parameter is the wrong one.