Robert Mosolgo

To my knowledge, batman.js is not maintained. For that reason, I don't suggest that you use it for a new project!

Jasmine-Friendly Batman.js Accessor Stubs

Batman.Object accessors are the bread and butter of batman.js. Stubbing them can make testing much easier.

I haven’t figured out Batman.TestCase yet, so I’m still using jasmine. Batman.TestCase includes stubAccessor out of the box, and I ported it to jasmine:

1
2
3
4
5
6
7
8
9
window.stubAccessor = (object, keypath) ->
  if object.prototype?
    console.warn "You're stubbing an accessor on #{object.name},
        which won't be un-stubbed when the example group finishes!
        Stub accessors on instances, not classes, if possible!"
  stub = spyOn(object.property(keypath), 'getValue')
  object.property(keypath).refresh()
  stub.calls.pop() # ^^ remove call from refresh
  stub

This way, the stub works just like normal jasmine spies:

1
2
3
4
5
record = new App.MyModel
stub = stubAccessor(record, 'myProperty').andReturn('stubbed!')
record.get('myProperty') # => "stubbed!"
record.get('myProperty')
stub.calls.length # => 2
1
2
3
4
5
record = new App.MyModel
stub = stubAccessor(record, 'myProperty').andCallThrough()
record.set('myProperty', "value!")
record.get('myProperty') # => "value!"
stub.calls.length # => 1

However, this stubAccessor doesn’t stub set! Maybe that’s a to-do, I haven’t needed it yet.