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

Allow for code coverage generation for the currently tested file only #127

Open 2press opened 3 years ago

2press commented 3 years ago

Using jestrunner.runOptions, it is currently possible to generate code coverage at the end of the test. This is, however, done for all files in the current project unless a file pattern is provided, which if one only seeks to test the coverage of the corresponding file, e.g., Code.tsx corresponding to Code.test.tsx, is file dependent. Could you add the option to generate the code coverage of the corresponding file only?

firsttris commented 3 years ago

could you provide some example command for Code.test.tsx and Code.tsx

isaiah-rsi commented 3 years ago

Suppose I had a source structure like

src\
    modules\
        module-a\
            components\
                MyComponent\
                    MyComponent.jsx
                    ...
test\
    modules\
        module-a\
            components\
                MyComponent\
                    MyComponent.test.jsx
                    ...

I would like to run

jest 'src/modules/module-a/components/MyComponent/MyComponent.test.jsx' --collectCoverageFrom='test/modules/module-a/components/MyComponent/MyComponent.jsx'

By right-clicking in the test file and selecting Run Jest File I would like a way to pass these options to the extension

carloschneider commented 2 years ago

Maybe a way is to implement the use of variables like this:

{
  "jestrunner.runOptions": [
    "--collectCoverageFrom='${projectPath}/test/${filePath}/${fileName}.jsx'"
  ]
}
Adam-Schlichtmann commented 2 years ago

Hello, this is something I would love to see work as well.

I tried the solution from @carloschneider above but, it doesn't seem to be filling in the template string with the actual paths.

Any help would be appreciated!

carloschneider commented 2 years ago

@Adam-Schlichtmann can you share your implementation?

Adam-Schlichtmann commented 2 years ago

@carloschneider

My folder structure is

src
| - screens
     | - Screen
          | - Screen.tsx
          | - index.ts
          | - utils
               | - index.ts
               | - numberUtil
                    | - numberUtil.ts
                    | - index.ts
                    | - __tests__
                        | - numberUtil.test.ts

I added this to my settings file

{
  "jestrunner.runOptions": ["--collectCoverageFrom='src/**/${fileName}/**/*'"],
}

When I run a test, using the run test button from within the file, no coverage is ran on any file.

The output to the console shows the jest args as this, which makes me think the ${fileName} is never being substituted in.

'--collectCoverageFrom=src/**/${fileName}/**/*'

To make sure it would work, I ran the following manually in the command line and everything worked as expected. Test was ran and coverage was ran only for files under the numberUtil folder.

yarn test src/**/numberUtil/**/* --collectCoverageFrom="src/**/numberUtil/**/*" 

Note: If I was looking at the code for the extension correctly, it seems like using ${fileName} would give me numberUtil.test.ts which would then not work anyway. I would love to see a list of what is available to use, assuming this is working.

Thanks for you time!

carloschneider commented 2 years ago

@Adam-Schlichtmann Now I understand what you meant.

Maybe a way to use variables in jestrunner.runOptions like:

{
  "jestrunner.runOptions": [
    "--collectCoverageFrom='${projectPath}/test/${filePath}/${fileName}.jsx'"
  ]
}

I just made a suggestion of the ideal configuration, the variables are not implemented yet on the project. I'll try implementing this. I believe this would work with a template parser function like this: https://gist.github.com/smeijer/6580740a0ff468960a5257108af1384e

But before I implement this, it would be great to know what @firsttris thinks about this solution.

carloschneider commented 2 years ago

We have a little problem here, analyzing the scenarios I found that in the case @isaiah-rsi it will be very difficult to deal with the src directory using my proposal, for example:

main file: /home/user/workspace/project/src/components/Input.tsx

test file: /home/user/workspace/project/test/components/Input.test.tsx

My proposal config:

{
  "jestrunner.runOptions": [
    "--collectCoverageFrom='${projectPath}/test/${filePath}/${fileName}.tsx'"
  ]
}

With the variables set the result will be:

$projectPath: /home/user/workspace/project/ $filePath: /src/components/Input.test.tsx (here is the problem) $fileName: Input

/home/user/workspace/project/test/src/components/Input.tsx

The src directory is part of filePath.

😞

Any suggestion?

carloschneider commented 2 years ago

We could use path.normalize but I don't think it will be possible to use .. after the src directory.

IIxauII commented 2 years ago

any update on this? Would be a great feature

sghsri commented 2 years ago

Would love for this feature to make it into the extension!

finnmerlett commented 2 years ago

This would be absolutely amazing to see implemented!

finnmerlett commented 2 years ago

I wrote a little bash script that is a perfect workaround in the meantime. Copy and customise the following file into an appropriate location, then set your "jestrunner.jestCommand" to "./.vscode/jest_single_coverage.sh <your normal test command>". I created it to just pull coverage from any files matching the filename with .test removed, but you can customise it however you want.

./.vscode/jest_single_coverage.sh :

#!/bin/bash

begins_with() { case $2 in "$1"*) true;; *) false;; esac; }
PATH_PREFIX='/Users' # this will vary based on your OS and computer setup

for ARG in $@; do
  if begins_with "$PATH_PREFIX" "$ARG"; then
    FILE_CHOSEN=$ARG;
  fi
done

# no specific test file supplied
if [ -z "$FILE_CHOSEN" ]; then
  # add a fallback after $@ here to still reduce coverage printout
  # somewhat (if you want), such as "changedSince=main"
  "$@";
  exit 0;
fi

# turn </Users/myname/folder/project/src/core/script>.test<.ts>
# into <script><.ts>
# (parts inside <..> are examples and can be anything)
TARGET_FILENAME="$(echo $FILE_CHOSEN | sed 's/.*\/\(.*\)\.test/\1/')"
"$@" "--collectCoverageFrom=**/$TARGET_FILENAME"

NOTE: just be aware that if you run this on one specific test in a file, the coverage will report your file's skipped tests as uncovered lines, damaging your beautiful coverage percentages. I'll probably just stick to using extension.runJestFile with this script.

firsttris commented 2 years ago

I don't like your solution.

Why not simply extend the extension? Instead of writing a bash script.

finnmerlett commented 2 years ago

I'm unfamiliar with VSCode extension development and don't want to put the time and energy into setting it up and learning it that it would require. This was a small quick patch-fix to add a way to get the functionality that hadn't seen any progress in months on the repo.

The script is here if people want to use it while the feature remains unimplemented. If you like the approach, you or someone else can replicate it in JS/TS and add it to the extension. Otherwise, feel free to ignore it. Makes no difference to me ☺️

firsttris commented 2 years ago

you are familiar with JS/TS development, that means you probably have the skills. the extension contains of just a few files. the readme contains anything you need to know. Maybe you think its super difficult but its not, let me tell you im also just a junior with vscode extensions.

finnmerlett commented 2 years ago

I might have a look at it at some point in the future, for now at least there's a quick workaround.

firsttris commented 2 years ago

that hadn't seen any progress in months on the repo.

you know open-source development means that everyone is allowed to contribute. furthermore im also actively looking for collaborators, inviting people who did good contributions.

if i would work on every feature request & issue create on the repo, it would be almost a full-time job. i at least try to sort, order and label them, to work on them at some point.

finnmerlett commented 2 years ago

I sense some saltiness in the messages from both of us πŸ˜… look, I get you do this for free too, and I love the extension - it's really super useful. That said, it's not a great look if your first response to someone volunteering a contribution is "why didn't you do more work". Everyone's entitled to do as much or as little as they want in these kinda spaces. And I will consider looking into adding it to the extension in the future.

firsttris commented 2 years ago

sorry mate

finnmerlett commented 2 years ago

Haha it's okay, happens to the best of us πŸ˜„ I had to delete my initial response to your first message because as soon as I re-read it I realised I was being hella reactionary and inflammatory

mhluska commented 2 years ago

I use this workaround: add a function like this to .zshrc or .bashrc:

function jt() {
    if [ "${#}" -lt 1 ]; then
        echo "Usage: ${0} test-filepath [remaining-jest-params]"
        return 1
    fi

    test_filepath="${1}"
    shift

    test_filename=$(basename "${test_filepath}")
    test_dir=$(dirname "${test_filepath}")
    extension="${test_filename##*.}"
    source_filename="${test_filename%.*.*}.${extension}"
    source_filepath="${test_dir}/../${source_filename}"
    relative_source_filepath=$(realpath --relative-to="$(npm root)/.." "${source_filepath}")

    $(npm bin)/jest "${test_filepath}" --coverage --collectCoverageFrom="${relative_source_filepath}" "${@}"
}

Then make jest-runner use that as the test command:

"jestrunner.jestCommand": "jt"
arminbashizade commented 3 weeks ago

@firsttris I started a PR to add this functionality https://github.com/firsttris/vscode-jest-runner/pull/372

firsttris commented 2 weeks ago

nice thanks!

arminbashizade commented 2 weeks ago

@firsttris it failed on publish, looks like the token is expired https://github.com/firsttris/vscode-jest-runner/actions/runs/11290782365/job/31403338425

firsttris commented 2 weeks ago

yes i need to optain a new one

firsttris commented 2 weeks ago

should be good now, added a new PAT to GIT