Quick answer: No.
Long answer: Yes, but it's not that clean or straight forward.
I have achieved this through three steps.
STEP 1:
You can achieve this by a bit of scripting. First you'll want to get a list of all the changed files through Git.
This can be achieved through a function like the below:
const util = require("util")
const exec = util.promisify(require("child_process").exec)
const detectChnagedFiles = async () => {
try {
const { stdout, stderr } = await exec("git diff origin/master --name-only")
if (stderr) {
throw new Error(stderr)
}
return stdout.replace(/\n/g, " ").replace(/client\//g, " ")
} catch (error) {
console.log(error)
}
}
STEP 2:
Secondly, you'd wanna get a list of related tests for those files like the below:
const findRelatedTests = async () => {
const changedFiles = await detectChnagedFiles()
try {
const { stdout, stderr } = await exec(`jest --listTests --findRelatedTests ${changedFiles}`)
if (stderr) {
throw new Error(stderr)
}
if (!stdout) {
console.log('No tests found for the changed files :)')
} else {
return stdout.replace(/\n/g, " ")
}
} catch (error) {
console.log(error)
}
}
STEP 3:
And finally you'd wanna feed all of those tests to jest to run;
const runRelatedTests = async () => {
const relatedTests = await findRelatedTests()
if (relatedTests) {
try {
const { stdout, stderr } = await exec(`jest --ci --coverage ${relatedTests}`)
if (stderr) {
throw new Error(stderr)
}
} catch (error) {
console.log(error)
}
}
}
One of the limitations of this implementation is that I"m always diffing against the master and that's not a good assumption. In special cases, one may chose to merge against another branch.
This can be handled in a few ways;
- If you're running a cli, pass the arguments to the cli and consume it in your script
- If you're running in pipeline like Gitlab and assuming that this is a MR/PR, consider using some available environment varibale ( in this case CI_MERGE_REQUEST_TARGET_BRANCH_NAME )