Last active
November 17, 2021 18:28
-
-
Save sawyerh/086ed9e9ff237b50975bd83a9527e4f2 to your computer and use it in GitHub Desktop.
Test to disallow .js files
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
import path from "path"; | |
import recursiveReadSync from "recursive-readdir-sync"; | |
type RelativeFilePath = string; | |
type AbsoluteFilePath = string; | |
const SRC_DIR = "../src/"; | |
const STORIES_DIR = "../storybook/stories/"; | |
/** | |
* Add a custom matcher so the test failure message is more useful. | |
* @see https://jestjs.io/docs/expect#expectextendmatchers | |
*/ | |
function toNotIncludeJsFiles(filePaths: string[]) { | |
const jsFilePaths = filePaths | |
.filter((filePath) => filePath.endsWith(".js")) | |
.map((filePath) => filePath); | |
const failureMessage = () => | |
`expected files to not include .js files. Received these .js files:\n\n${jsFilePaths.join( | |
"\n" | |
)}`; | |
return { | |
message: failureMessage, | |
pass: jsFilePaths.length === 0, | |
}; | |
} | |
expect.extend({ | |
toNotIncludeJsFiles, | |
}); | |
declare global { | |
// eslint-disable-next-line @typescript-eslint/no-namespace | |
namespace jest { | |
interface Matchers<R> { | |
toNotIncludeJsFiles(): R; | |
} | |
} | |
} | |
describe("File extensions", () => { | |
it.each([SRC_DIR, STORIES_DIR])( | |
"does not include .js files in %s", | |
(targetDir) => { | |
const filePaths: Array<[RelativeFilePath]> = recursiveReadSync( | |
path.resolve(__dirname, targetDir) | |
).map((filePath: AbsoluteFilePath) => | |
// Make the path prettier for the test output: | |
path.relative(__dirname, filePath).replace(targetDir, "") | |
); | |
expect(filePaths).toNotIncludeJsFiles(); | |
} | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment