marilari88 / neotest-vitest

Vitest adapter for Neovim Neotest plugin
92 stars 34 forks source link

Tests are not run (`package.json not found`) #20

Closed j-a-m-l closed 1 year ago

j-a-m-l commented 1 year ago

When I save a file I see this message:

package.json not found
"tests/example.spec.ts" 7L, 100B written
Press ENTER or type command to continue

It happens independently of its location in the project.

The content is not relevant (I've tried with several files).

Tests are not executed when saving these files or using the summary.

marilari88 commented 1 year ago

Hi @j-a-m-l do you have a public repo that I can test? This error occours when the adapter cannot find a valid package.json to look into for check vitest dependency

j-a-m-l commented 1 year ago

Thanks, @marilari88.

I've just pushed the project to https://gitlab.com/meaningfuldata/antlr-monaco.

boydaihungst commented 1 year ago

@marilari88 you should check file_path match file extension before check hasVitestDependency. Change logic check __test__ folder and extension a little bit. And remove the line print("package.json not found") to prevent that message show up everytime open a file that matched parttern but doesn't installed vitest package.

init.lua

local function hasVitestDependency(path)
  local rootPath = lib.files.match_root_pattern("package.json")(path)

  if not (rootPath) then
    -- print("package.json not found")
    return false
  end

  local success, packageJsonContent = pcall(lib.files.read, rootPath .. "/package.json")
  if not success then
    print("cannot read package.json")
    return false
  end

  local parsedPackageJson = vim.json.decode(packageJsonContent)

  if parsedPackageJson["dependencies"] then
    for key, _ in pairs(parsedPackageJson["dependencies"]) do
      if key == "vitest" then
        return true
      end
    end
  end

  if parsedPackageJson["devDependencies"] then
    for key, _ in pairs(parsedPackageJson["devDependencies"]) do
      if key == "vitest" then
        return true
      end
    end
  end

  return false
end

---@param file_path? string
---@return boolean
function adapter.is_test_file(file_path)
  if file_path == nil then
    return false
  end
  local is_test_file = false
  local is_test_folder = false

  if string.match(file_path, "__tests__") then
    is_test_folder = true
  end

  for _, x in ipairs({ "spec", "test" }) do
    for _, ext in ipairs({ "js", "jsx", "coffee", "ts", "tsx" }) do
      if string.match(file_path, "%." .. x .. "%." .. ext .. "$") then
        is_test_file = true
        goto matched_pattern
      end
    end
  end
::matched_pattern::
  if (is_test_file or is_test_folder) and hasVitestDependency(file_path) then
    return true
  end

  return false
end
marilari88 commented 1 year ago

Hi @boydaihungst! Great job! I have sent you some comments. Thanks for your appreciated contribution!

j-a-m-l commented 1 year ago

Thanks @marilari88 and @boydaihungst. That has solved one of my problems.