NodeJS 如何在重复循环中以非并行模式运行摩卡咖啡测试?

juzqafwq  于 2023-02-15  发布在  Node.js
关注(0)|答案(1)|浏览(142)

我想在一个循环中以非并行模式重复运行一个摩卡测试。但是看起来测试只在第一次迭代时被添加到摩卡中。日志显示0个已运行的测试。
下面是主文件(需要安装摩卡):

const fs = require('fs')
const path = require('path');
const Mocha = require('mocha');

getFiles = dir => { // returns tests files as an array
    const files = []
    let resolvedPath = path.resolve(dir);
    
    for (const file of fs.readdirSync(dir)) {
        const fullPath = resolvedPath + '/' + file
        if (fs.lstatSync(fullPath).isDirectory())
            getFiles(fullPath).forEach(x => files.push(file + '/' + x))
        else if (file.endsWith('.js')) {
            files.push(fullPath)
        }
    }
    return files
}

function delay(time) { // used for sleep within the start function
  return new Promise(resolve => setTimeout(resolve, time));
} 

async function start(testsPath) {
    
    let testFiles = getFiles(testsPath);
    let failedTestsCount = -1;
    
   while(true) {
        console.log("starting a new iteration")
        let mocha = await new Mocha();
        for (let i = 0; i < testFiles.length; i++) {
            mocha.addFile(testFiles[i]);
        }
        
        mocha.parallelMode(false);

        await mocha.run(failed => {
            failedTestsCount = failed;
        });
        console.log("Failed tests: " + failedTestsCount)
        await delay(1000*60) // 1 minute   
    }      
}

start('./tests');

还有一个名为tests的子目录,用于存储测试文件,为了简单起见,它只包含一个文件(需要安装chai):

let expect = require("chai").expect;

describe("Very Simple Tests", async function() {  

    it("passing", async function() {
        expect(true).to.equal(false);
    });

    it("failing", async function() {
        expect(true).to.equal(true);
    });  
});

我得到了以下输出(仅在第一次迭代时加载测试):

Very Simple Tests
    1) passing
    ✔ failing

  1 passing (3ms)
  1 failing

  1) Very Simple Tests
       passing:

      AssertionError: expected true to equal false
      + expected - actual

      -true
      +false
      
      at Context.<anonymous> (tests/tests.js:6:25)
      at process.processImmediate (node:internal/timers:476:21)


starting a new iteration
Failed tests: 1

  0 passing (0ms)

奇怪的是,在并行模式下,它们运行正常,但在某些情况下,我需要一个连续模式。我尝试了一些配置,但似乎没有帮助。
对于我来说,通过shell脚本和命令行选项运行它们远非最佳选择,因为我需要通过express中的端点使结果可见。
我怎样才能让它在非并行模式下运行?

ggazkfy8

ggazkfy81#

我需要在循环中添加unloadFiles(或dispose):

while(true) {
        console.log("starting a new iteration")
        let mocha = await new Mocha();
        for (let i = 0; i < testFiles.length; i++) {
            mocha.addFile(testFiles[i]);
        }
        
        mocha.parallelMode(false);

        await mocha.run(failed => {
            failedTestsCount = failed;
        });
        console.log("Failed tests: " + failedTestsCount)
        mocha.unloadFiles();
        await delay(1000*60) // 1 minute   
    }

相关问题