美文网首页
实现执行所有文件测试用例的脚本

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

作者: sweetBoy_9126 | 来源:发表于2024-04-13 17:50 被阅读0次

实现逻辑

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()")
}

相关文章

网友评论

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

      本文链接:https://www.haomeiwen.com/subject/taflxjtx.html