[vim] Jump to test file

[vim] Jump to test file

Today a colleague was showing me a shortcut in his editor to jump from a file to its related test file. I thought it was pretty good idea to try out myself. Currently I'm searching for all references of a function and select the test file. Another method is to do a fuzzy search on the file name + test and that works quite fast already. I won't settle for that, so let's write a mapping and make the shortcut in vim.

The assumption is the filename of the test is subject.test.ts and the code being tested is in subject.ts. The location of the test file should be in the same directory (or use :set path+=** if you put the test files somewhere else). The first step is get the related file name.

:echo expand('%:t:r') .'.test.ts'

The expand function will return the filename minus the extension. I'll concatenate with .test.ts, because I work with typescript. The second step is to open the file.

:find subject.test.ts

Too bad we can't replace subject.test.ts with the first snippet, because it will search for a file with the code as filename. The third step will solve this problem.

:execute ':find ' . expand('%:t:r') . '.test.ts'

This command will take a string, executes it and does what we want: find the related test file and opens it. The fourth step is to assign this line of code to a mapping. I'm using \ as the leader and will use <leader>t as shortcut.

nmap <leader>t :execute ':find ' . expand('%:t:r') . '.test.ts'<CR>

That's just it! Ok, it might not be perfect, but probably good enough in most cases. Now I've three methods to jump to a test file, but this one costs only two key presses and I'm looking forward to using it.

To view or add a comment, sign in

More articles by Michiel Vos

Explore content categories