Created
April 18, 2024 18:29
-
-
Save Zodiase/04bcab57ddf2134e8f9395db7c1d3756 to your computer and use it in GitHub Desktop.
Skip test file unless explicitly targeted. This allows an "unfriendly" test file to live along other test files and not interfere "run all tests".
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This test file should only be run explicitly. When that's the case, the command should look something like: | |
* npm run test ./some/test/folder/test-something.js | |
* which means the process arguments should be something like: | |
* [ "some/path/node", "some/path/mocha", "./some/test/folder/test-something.js" ] | |
* but we can not assume the third argument would always be a file path. | |
* So to evaluate this flag, the function should: | |
* 1. Check if argv[2] is likely a file path pointing at this file. | |
* 2. resolve argv[2] and compare with this file's absolute path. | |
*/ | |
const isThisTestFileRunExplicitly = (() => { | |
const possibleFilePath = process.argv[2]; | |
// Should at least have 3 arguments. | |
if (!possibleFilePath) { | |
return false; | |
} | |
// Possible file path should end with this file name. | |
if (!( | |
// The test target may not have an extension. | |
possibleFilePath.endsWith(path.extname(__filename)) | |
// Compare with extension. | |
? possibleFilePath.endsWith(`/${path.basename(__filename)}`) | |
// Compare without extension. | |
: possibleFilePath.endsWith(`/${path.basename(__filename, path.extname(__filename))}`) | |
)) { | |
return false; | |
} | |
const normalizedFilePathWithExtname = path.normalize( | |
possibleFilePath.endsWith(path.extname(__filename)) | |
? possibleFilePath | |
// : possibleFilePath, // Replace the line below with this line to test this flag by setting it to false when an extension is not specified. | |
: `${possibleFilePath}${path.extname(__filename)}`, | |
); | |
const absoluteFilePath = path.isAbsolute(normalizedFilePathWithExtname) | |
? normalizedFilePathWithExtname | |
: path.resolve(process.cwd(), normalizedFilePathWithExtname); | |
return absoluteFilePath === __filename; | |
})(); | |
(isThisTestFileRunExplicitly ? describe : describe.skip)("module being tested", function() { | |
// ... | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment