Skip to content

Instantly share code, notes, and snippets.

@sawyerh
Last active November 17, 2021 18:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sawyerh/086ed9e9ff237b50975bd83a9527e4f2 to your computer and use it in GitHub Desktop.
Save sawyerh/086ed9e9ff237b50975bd83a9527e4f2 to your computer and use it in GitHub Desktop.
Test to disallow .js files
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