Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

jestjs - How does jest --findRelatedTests work under the hood?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...