Find and run the tests that cover a space separated list of source
files that were passed in as arguments. Useful for pre-commit hook
integration to run the minimal amount of tests necessary.
This is in official docs, but how does this work? Does it analyze all the imports in my project and only runs tests that import the file I want to test? That's how I would write it, but is it really working like that?
Related question-does it use a cache when finding related tests?
I'v been stuck with the same question for the last few days. After digging through the Jest source code, I think I have a pretty good idea of what's going on.
When running --findRelatedTests path/to/src-code.js
, the first thing that happens is Jest creates an instance of an internal package, jest-resolve-dependencies
. It's a pretty straightforward class with two methods: resolve
and resolveInverse
.
findRelatedTests
calls resolveInverse
on the paths you provided, looking up every source and test file that requires your file, in our example path/to/src-code.js
. This lookup relies directly on some Jest configuration, specifically roots
and/or rootDir
, to help resolve paths.
If the found file is a test file, Jest runs it, simple enough. If the found file is a source file, call it found-file.js
, then any test files that import found-file.js
and the test files that import any of the source files that themselves import found-file.js
will be run.
It's a clever implementation of, as the maintainers put it, a resolver of "transitive inverse dependencies". You can see for yourself in this while
loop.