3

I'm interested to know if there is any way to mock Vimscript functions for testing. I know there are frameworks like vader.vim, but nothing is said about mocking.

boechat107
  • 1,654
  • 14
  • 24

1 Answers1

4

You can redefine any existing user function with :function!. So, for example,

function! Mock(name, Hook) abort
    " save a reference to original function
    let l:Orig = funcref(a:name)
" overwrite function
let l:text =<< trim EOF
        function! %s(...) abort closure
            let l:oldresult = call(l:Orig, a:000)
            let l:newresult = call(a:Hook, [l:Orig, l:oldresult] + a:000)
            return l:newresult isnot v:null ? l:newresult : l:oldresult
        endfunction
EOF
    execute printf(join(l:text, "\n"), a:name)
endfunction

" silly test
function! Test(p1, p2) abort
    return a:p1 * a:p2
endfunction

function! MyHook(Orig, result, ...) abort
    echo 'Calling' get(a:Orig, 'name') 'with params' a:000 'produced' a:result
    " remember: default return value is zero, not v:null
    return a:result * 2
endfunction

call Mock('Test', funcref('MyHook'))
echo Test(6, 7)

" Calling Test with params [6, 7] produced 42
" 84
Matt
  • 13,674
  • 1
  • 18
  • 27
  • I've implemented a simplified version of this idea: https://github.com/blp1526/storage.vim/blob/master/spec/storage_spec.vim#L6 – boechat107 Aug 21 '20 at 23:21