lunarmodules/luassert

Create spy/stub that replaces an original function with another function?

mrrogge opened this issue · 1 comments

From the busted docs:

Spies are essentially wrappers around functions that keep track of data about how the function was called, and by default calls the function.

Stubs act similarly to spies, except they do not call the function they replace. This is useful for testing things like data layers.

So spies call the original function, and stubs do not. I'm wondering if there is a way to replace a function with a spy or stub that also calls a new function. For example:

local testModule = {
    testFunction=function() end
}

spy.on(testModule, 'testFunction', function() print('replaced original') end)

For now I'm just monkeypatching the original as a workaround, but it would be nice if I could use the revert() to undo the change at the end of the test.

Edit: reworded my question a little bit

Aha, just found out this works:

local testModule = {
    testFunction=function() end
}

stub(testModule, 'testFunction', function() print('replaced original') end)
testModule.testFunction()    --'replaced original'

If I find time I'll do a PR to update the docs with this info. I'll go ahead and close the issue.