firsttris / vscode-jest-runner

Simple way to run or debug one or more tests from context menu, codelens or command plalette
https://marketplace.visualstudio.com/items?itemName=firsttris.vscode-jest-runner
MIT License
265 stars 124 forks source link

RFC: Run from nearest package.json #340

Closed cdaringe closed 8 months ago

cdaringe commented 10 months ago

Problem

In monorepos, some modules are only available in the sub-package under test, thus aren't available if cwd the monorepo root.

For example:

<root>
  packages/
     foo/
       package.json
       __tests__/
         foo.spec.ts
     bar/
       package.json
       __tests__/
         bar.spec.ts

If cwd is <root>, and foo.spec.ts calls jest.mock on a package that is only present packages/foo/node_modules, jest crashes!

Discussion

Support for a feature like cwdNearestPackageJson: true could easily:

With such a feature, monorepo users could run a test from any sub-package, and reliably run in the same pwd and node_modules context as if they had just cd <path-to-package> && jest .!

domsleee commented 9 months ago

I'll reopen this one for discussion 👍

I think this case is already supported, but I could be wrong.

If you try it with jestrunner.changeDirectoryToWorkspaceRoot, it will run cd <path> before running the jest command.

You can see here it is falling back to currentPackagePath, which upsearches for package.json:

https://github.com/firsttris/vscode-jest-runner/blob/43cc89b213698c2971b8b3437345ad6d04b1eb6d/src/jestRunnerConfig.ts#L51-L77

Based on the code, perhaps the current docs could be improved:

jestrunner.changeDirectoryToWorkspaceRoot | Changes directory to workspace root before executing the test -- | --

I think this setting should really be:

Changes directory to the resolved project path. The fallback order is jestrunner.projectPath, falling back to the nearest package.json, falling back to the workspace root.

Does this cover your use case? Thanks