Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
jasmine.Spy.prototype.andReturnDeferred = ->
@deferreds = []
@resolve = =>
unless @deferreds.length > 0
throw "Cannot resolve, #{@identity} was not called"
dfr = @deferreds.shift()
dfr.resolve()
@reject = =>
unless @deferreds.length > 0
throw "Cannot reject, #{@identity} was not called"
dfr = @deferreds.shift()
dfr.reject()
@andCallFake =>
dfr = new $.Deferred
@deferreds.push(dfr)
dfr
describe "Spies", ->
describe "andReturnDeferred", ->
beforeEach ->
@obj = { doAsync: (->) }
spyOn(@obj, "doAsync").andReturnDeferred()
@observer = (->)
it "should trigger success callbacks when resolved", ->
@observer = jasmine.createSpy("successObserver")
@obj.doAsync().done(@observer)
expect(@observer).not.toHaveBeenCalled()
@obj.doAsync.resolve()
expect(@observer).toHaveBeenCalled()
it "should trigger failure callbacks when rejected", ->
@observer = jasmine.createSpy("failureObserver")
@obj.doAsync().fail(@observer)
expect(@observer).not.toHaveBeenCalled()
@obj.doAsync.reject()
expect(@observer).toHaveBeenCalled()
it "should fail when trying to resolve/reject before spied function was called", ->
expect(=> @obj.doAsync.resolve()).toThrow("Cannot resolve, doAsync was not called")
expect(=> @obj.doAsync.reject()).toThrow("Cannot reject, doAsync was not called")
it "should run callbacks in order of registration", ->
@observer1 = jasmine.createSpy("observer1")
@obj.doAsync().done(@observer1)
@observer2 = jasmine.createSpy("observer2")
@obj.doAsync().done(@observer2)
@obj.doAsync.resolve()
expect(@observer1).toHaveBeenCalled()
expect(@observer2).not.toHaveBeenCalled()
@obj.doAsync.resolve()
expect(@observer2).toHaveBeenCalled()
expect(=> @obj.doAsync.resolve()).toThrow("Cannot resolve, doAsync was not called")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.