實現(xiàn)執(zhí)行所有文件測試用例的腳本

實現(xiàn)邏輯

1. 獲取到所有的測試腳本文件 *.spec.js

  • 借助 glob 庫
import glob from 'glob'

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

2.得到每個文件里的內(nèi)容

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

3.執(zhí)行文件里的內(nèi)容

new Function(fileContent)()

報錯:SyntaxError: Cannot use import statement outside a module
at new Function (<anonymous>)
因為我們文件里有 Import 而 import 不能包裹在函數(shù)內(nèi)執(zhí)行

  • 解決方式:使用打包器
    安裝 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()")
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容