Skip to content

Instantly share code, notes, and snippets.

@zapu
Last active August 29, 2015 14:00
Show Gist options
  • Save zapu/11304746 to your computer and use it in GitHub Desktop.
Save zapu/11304746 to your computer and use it in GitHub Desktop.
mocks
mockery = (func) ->
mocks = [{f: func}]
ret = () ->
mock = mocks[0]
unless mock
throw new Error('No mocks left')
unless mock.forever
mocks.splice(0, 1)
return mock.f.apply @, arguments
ret.more = (func) ->
if mocks.length == 1 and mocks[0].forever
throw new Error('Mock already is forever')
mocks.push {f: func}
ret.forever = (func) ->
unless func
mocks[mocks.length - 1].forever = true
return
ret.more func
ret.forever()
ret.is_done = (test) ->
if mocks.length == 1 and mocks[0].forever
return
test.equal mocks.length, 0
return ret
mockery.args = (test) ->
args = Array::slice.call(arguments, 1)
return ->
test.equal arguments.length, args.length, 'argument count'
for i in [0..arguments.length - 1]
test.deepEqual arguments[i], args[i], 'argument deepequal'
return undefined
mockery.ret = (ret, func) ->
return ->
func.apply undefined, arguments
return ret
exports.testMockery = (test) ->
a = mockery mockery.args test, 1, 2
a.more mockery.ret true, mockery.args test, 3, 4
a.forever (-> false)
test.equal a(1, 2), undefined
test.equal a(3, 4), true
test.equal a(5), false
test.equal a(6, 6), false
a.is_done test
test.done()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment