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:
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:
record = new App.MyModel
stub = stubAccessor(record, 'myProperty').andReturn('stubbed!')
record.get('myProperty') # => "stubbed!"
record.get('myProperty')
stub.calls.length # => 2
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.