nodejs-testing icon indicating copy to clipboard operation
nodejs-testing copied to clipboard

Is there a way to run tests from project directory?

Open Niakr1s opened this issue 10 months ago • 4 comments

Hello! Thanks for your extension!

I have a problem. I have test data in '{project_dir}/testdata' folder, and I want them to load it from filesystem in tests. But it seems that Test Explorer runs tests with cwd set to test file' directory.

For example, if I try to do this in file 'tests/foo/bar.test.js':

let raw = readFileSync('./testdata/raw.json', 'utf-8');

I'm getting cryptic window with message: 'The editor could not be opened because the file was not found.' Command 'node --test' from terminal, if I run it from project directory, works great though.

However, if I change filepath to relative:

let raw = readFileSync('../../testdata/raw.json', 'utf-8');

it works smoothly.

I made a small investigation: command process.cwd(), executed in a debug console, gets me directory of a test file. In comparison, same command when I run tests with jest, results in the project directory.

So, is it possible to fix it so that tests always run from project directory?

Niakr1s avatar Mar 27 '24 12:03 Niakr1s

Upd: I ended up in using pkg-dir module, it works good.

Niakr1s avatar Mar 27 '24 20:03 Niakr1s

Yea, I agree that tweaking this makes sense. I will probably have some "projectRoot" setting, defaulting to your workspace folder, that controls the cwd among other things (things that we naively root at the workspace folder today)

connor4312 avatar Mar 27 '24 20:03 connor4312

That would've been great!

Niakr1s avatar Mar 27 '24 20:03 Niakr1s

Great extension, thank you for your work!

Running in to this same issue - tests are all written assuming execution from projectRoot and fail when using test runner. Current workaround is:

settings.json

{
    "nodejs-testing.pretest": [
        "./test-prep.sh"
    ]
}

test-prep.sh

cd ..

techfg avatar Apr 12 '24 07:04 techfg

ty @connor4312!!

techfg avatar Aug 15 '24 03:08 techfg