Search code examples
vimvim-plugin

Is there a way to mock Vimscript/VimL functions?


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.


Solution

  • 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