实现执行所有文件测试用例的脚本

2024-04-13  本文已影响0人  sweetBoy_9126

实现逻辑

1. 获取到所有的测试脚本文件 *.spec.js

import glob from 'glob'

const files = glob.sync("*.spec.js")
console.log(files, 'ffff')

2.得到每个文件里的内容

import fs from 'fs/promises'
const fileContent = await fs.readFile("first.spec.js", "utf-8")
console.log(fileContent)

3.执行文件里的内容

new Function(fileContent)()

报错:SyntaxError: Cannot use import statement outside a module
at new Function (<anonymous>)
因为我们文件里有 Import 而 import 不能包裹在函数内执行

import { build} from 'esbuild'
await runModule(fileContent)
 async function runModule(fileContent) {
  const result = await build({
    stdin: {
      contents: fileContent,
      resolveDir: process.cwd(),
    },
    // 不写入文件
    write: false,
    // 将文件都打包到一个文件里
    bundle: true,
    target: "esnext"
  })
  new Function(result.outputFiles[0].text)()
}

4. 遍历文件

for(const file of files) {
  const fileContent = await fs.readFile(file, "utf-8")
  await runModule(fileContent)
}

5. 不使用run

for(const file of files) {
  const fileContent = await fs.readFile(file, "utf-8")
  await runModule(fileContent + ";import {run} from './core.js'; run()")
}
上一篇下一篇

猜你喜欢

热点阅读