From 247bd26c8b6fbc00c911a2cb87aacd39057bbb6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Matte?= Date: Sun, 4 Dec 2022 16:30:05 -0500 Subject: [PATCH] Add easy suite testing --- README.md | 15 +++++++++++++++ index.js | 3 ++- suite.js | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 suite.js diff --git a/README.md b/README.md index a2ce049..7854285 100644 --- a/README.md +++ b/README.md @@ -54,3 +54,18 @@ suite.js const { test } = await import("test.js"); await test.run(consolereporter()); ``` + +## Hot to easily run a suite of multiple test + +test.js + +```js +... +``` + +suite.js + +```js +import { suite } from "metaltest"; +await suite(); // Will run all test that are in the current folder recursively +``` diff --git a/index.js b/index.js index 6824287..01c40ad 100644 --- a/index.js +++ b/index.js @@ -3,6 +3,7 @@ import { consolereporter } from './consolereporter.js' import { linereporter } from './linereporter.js' import { totalreporter } from './totalreporter.js' import { runifmain } from './runifmain.js' +import { suite } from './suite.js' const noreporter = { start: (title) => { }, @@ -67,5 +68,5 @@ const metaltest = (title) => { return runner } -export { metaltest, consolereporter, linereporter, totalreporter, runifmain } +export { metaltest, consolereporter, linereporter, totalreporter, runifmain, suite } export default metaltest \ No newline at end of file diff --git a/suite.js b/suite.js new file mode 100644 index 0000000..443d8de --- /dev/null +++ b/suite.js @@ -0,0 +1,49 @@ +import { readdir } from 'node:fs/promises' +import { join } from 'node:path' +const walkDir = async function* (dir) { + const files = await readdir(dir, { withFileTypes: true }) + + for (const file of files) { + if (file.isDirectory()) { + yield* walkDir(join(dir, file.name)) + } else { + yield join(dir, file.name) + } + } +} + +import { fileURLToPath } from 'node:url' +import { dirname } from 'node:path' +const getStackAbsolutePaths = () => { + const old = Error.prepareStackTrace + Error.prepareStackTrace = (_, stack) => stack + const stack = new Error().stack + Error.prepareStackTrace = old + + return stack + .map(cs => cs.getFileName()) + .filter(filename => filename?.startsWith('file://')) + .map(filename => dirname(fileURLToPath(filename))) +} + +import { consolereporter, totalreporter } from 'metaltest' +const suite = async (folder = '.') => { + const absolutePaths = getStackAbsolutePaths() + const absolutePath = absolutePaths[2] + + const total = totalreporter() + + for await (const file of walkDir(folder)) { + if (file.includes('node_modules')) continue + if (file.startsWith('.git')) continue + if (!file.endsWith('test.js')) continue + + const module = join(absolutePath, file) + const { test } = await import(module) + await test.run(consolereporter(), total) + } + + console.log(total.msg()) +} + +export { suite } \ No newline at end of file