run-node-tests.mjs 1.36 KB
import { readdir, stat } from 'node:fs/promises'
import path from 'node:path'
import { spawn } from 'node:child_process'

async function collectTests(entryPath) {
  const absolutePath = path.resolve(entryPath)
  const entry = await stat(absolutePath)
  if (entry.isFile()) {
    return absolutePath.endsWith('.test.mjs') ? [absolutePath] : []
  }

  const results = []
  for (const child of await readdir(absolutePath, { withFileTypes: true })) {
    const childPath = path.join(absolutePath, child.name)
    if (child.isDirectory()) {
      results.push(...(await collectTests(childPath)))
    } else if (child.isFile() && child.name.endsWith('.test.mjs')) {
      results.push(childPath)
    }
  }
  return results
}

const roots = process.argv.slice(2)
if (!roots.length) {
  throw new Error('Provide at least one test directory or .test.mjs file')
}

const testFiles = (
  await Promise.all(roots.map(entryPath => collectTests(entryPath)))
)
  .flat()
  .sort()

if (!testFiles.length) {
  throw new Error(`No .test.mjs files found under: ${roots.join(', ')}`)
}

const child = spawn(
  process.execPath,
  ['--experimental-detect-module', '--test', ...testFiles],
  {
    stdio: 'inherit',
    shell: false
  }
)

child.on('error', error => {
  throw error
})

const exitCode = await new Promise(resolve => {
  child.on('exit', code => resolve(code ?? 1))
})
process.exitCode = exitCode