Dalius's blog

Wednesday, October 14, 2020

Running tests in Vim

Recently I had discussion with friends how testing can be improved while developing using Vim. As front-end developer I usually split my tmux into two panes and run Vim in one pane and run jest tests in watch mode in another pane.

This approach is working quite well for me (and other people) but there is zero integration with editor. So while playing around I have enhanced Vim with this little script that searched for right pane (Jest pane in my case) for filename with line and column number (e.g. src\some.test.ts:12:20) and jumps to it:

function! OpenFailingTest()
  let lastFile = system("tmux select-pane -L && tmux capture-pane -pJ -S - | rg -o '[[:alnum:]_.$&+=/@-]*:[0-9]*:[0-9]*' | tail -n 1 && tmux select-pane -R")
  let path = split(lastFile, ':')
  if filereadable(path[0])
    exe 'e ' . path[0]
    call cursor(str2nr(path[1]), str2nr(path[2]))
  else
    echo "File not found: " . lastFile
  endif
endfunction

map <leader>t :call OpenFailingTest()<cr>

This can be improved a lot but I have left this task for the future. I hope you will find it useful.

Alternative I have considered

One of the alternative I have looked at is vim-test. While it looks like a mature project as new user I have found some minor problems with this project:

  • There is no way to know what command it will try to use (jest, react-script?) instantly. E.g. TestInfo command similar to AleInfo would be useful here.

  • You are limited to tools that are supported by vim-test and if your tool is not supported you are almost out of luck.

  • Lastly jest errors without reporters are poorly supported.

Lastly you are limited to running tests in your file, suite or single test while Jest itself allows running tests for changed code or only failing tests.