[英]How to run a .js file containing a Mocha suite multiple times in a loop?
我有多個 .js 測試文件,我希望能夠多次運行每個文件中的測試。 例如,我想連續運行 5 次或 10 次。 即使它一次只是一個文件,但同一個文件多次。
我試圖從 memory 卸載模塊,然后多次再次加載它以查看它是否有效,但它沒有。 查看:
const testFilePath = './myFileWithOneMochaTestSuit.js';
for(let i = 0; i < 5; i++) {
delete require.cache[require.resolve(test)]; // Unloading the module in memory
require(testFilePath);
}
我之所以要這樣做是因為我有一些有時會失敗的集成測試。 我希望能夠多次運行這些測試,因為我需要在它們失敗時分析它們。
我所有的測試文件看起來像這樣:
// test1.js
describe('test suit 1', () => {
//...
before(() => {
//...
});
it(`test 1...`, async () => {
//...
});
it('test 2', () => {
//...
});
// more tests
});
// test2.js
// test2.js
describe('test suit 2', () => {
//...
before(() => {
//...
});
it(`test 1...`, async () => {
//...
});
it('test 2', () => {
//...
});
// more tests
});
所以,我需要的是能夠連續多次在test1.js
中運行測試套件。 然后連續多次test2.js
。 等等。
我無法做到這一點。
任何幫助,將不勝感激。
我嘗試多次加載require
的文件,但它們只運行一次,第一次。
我嘗試刪除 memory 中的緩存模塊並使用require
再次加載它,但沒有用。
詭異的! 一旦我將require
的返回值分配給一個變量並像這樣打印它,它就會突然開始工作:
for(let i = 0; i < 5; i++) {
delete require.cache[require.resolve(testFilePath)]; // Unloading the module in memory
const m = require(testFilePath);
console.log(m);
}
但后來我刪除了console.log(m)
以查看它是否繼續工作,並且確實如此:
for(let i = 0; i < 5; i++) {
delete require.cache[require.resolve(testFilePath)]; // Unloading the module in memory
const m = require(testFilePath);
}
最后,我刪除了const m =
以查看它是否繼續工作,並且確實如此!
for(let i = 0; i < 5; i++) {
delete require.cache[require.resolve(testFilePath)]; // Unloading the module in memory
require(testFilePath);
}
所以我基本上回到了我開始的地方,但現在它正在工作並加載模塊並卸載測試文件並根據需要多次運行測試。
我不知道這是怎么發生的,代碼基本上沒有區別,但我很高興它發生了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.