Categories
Software vim

Save/write all before test in Neotest

Neotest is an excellent plugin for working with tests in a variety of languages in Neovim, but it was driving me mad having to remember to run :wa before running any tests. Why would anyone want to edit a file then run tests against the last saved version rather than the one in the editor?

Anyway, after a bit of familiarisation with how the lua config for lazy.nvim works, it turned out to be pretty easy to override the default keybindings that run tests (copied from the full spec in the LazyVim docs for Neotest) to save everything first. I ended up with this in ~/.config/nvim/lua/plugins/neotest.lua:

return {
  "nvim-neotest/neotest",
  keys = {
    {
      "<leader>tt",
      function()
        vim.cmd("wa")
        require("neotest").run.run(vim.fn.expand("%"))
      end,
      desc = "Run File (Neotest)",
    },
    {
      "<leader>tT",
      function()
        vim.cmd("wa")
        require("neotest").run.run(vim.uv.cwd())
      end,
      desc = "Run All Test Files (Neotest)",
    },
    {
      "<leader>tr",
      function()
        vim.cmd("wa")
        require("neotest").run.run()
      end,
      desc = "Run Nearest (Neotest)",
    },
    {
      "<leader>tl",
      function()
        vim.cmd("wa")
        require("neotest").run.run_last()
      end,
      desc = "Run Last (Neotest)",
    },
  },
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.