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

实现逻辑

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

  • 借助 glob 库
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 不能包裹在函数内执行

  • 解决方式:使用打包器
    安装 esbuild
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()")
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容