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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…