簡體   English   中英

如何在Mocha的函數中正確放置測試套件?

[英]How to correctly put test suites in functions in mocha?

我對Mocha相當陌生,整個夏天我一直在與之合作,為Web應用程序中的功能編寫動態測試用例。 基本上,我可以發送請求並獲取所有可以發送的值。 因此,我一直使用它來遍歷和測試所有內容。 為了簡化操作,我使用測試套件和一些變量創建了一個函數,該函數應該可以運行所有測試。 這種工作方式是有效的,我的意思是說它可以正確運行所有測試。 但是,它會一直等到所有其他原因都已運行之后,這會導致我嘗試執行的操作出現問題。 我已經簡化了一些基本的代碼:

function test(){
    //Testing suite to test through a certain functionality using different variables
    describe('inner',function(){
        it('test3',function(){
            console.log('\ninner test');
        });
    });
}
function entityLoop() {
    describe('outer',function(){
        //Get field values from an http request
        it('test1',function(){
            console.log('\ntest1');
        });
        it('test2',function(){
            console.log('\ntest2');
        });

        //This MUST run after the other two tests, as those tests get the values needed to run the following tests
        //I know it's typically bad practice to make dependent tests, but that's how we're dynamically creating the tests
        after(function(){
            //Use field values in a testing suite
            console.log('after test');
            test();
        })
    })
}

describe("Overall loop",function(){
    //Need to loop through a testing suite, changing some variables each time
    for(var i = 0; i < 5;i++){
        entityLoop();
    }

});

這是我從中得到的輸出:

test1
test2
after test
test1
test2
after test
test1
test2
after test
test1
test2
after test
test1
test2
after test
inner test
inner test
inner test
inner test
inner test
Process finished with exit code 0

我不明白為什么最后要連續輸出5次“內部測試”,而不是每次都在“測試之后”輸出。 任何輸入,不勝感激。

您的代碼正在調用after鈎子中的describeit 它不會使測試套件崩潰,但不是Mocha明確支持的使用模式。 因此,它不會執行您期望的操作。

您得到的結果是因為describe(name, fn)這樣做的:

創建一個名為name的測試套件。 將其添加到當前正在定義的套件中。 將新套件推入套件堆棧。 致電fn 彈出套件堆棧。

“當前正在定義的套件”是套件堆棧頂部的套件。 摩卡(Mocha)維護着一堆套房。 它最初包含Mocha創建的包含所有測試的頂級隱式套件。 (因此,您可能有一個根本不使用describe的測試文件,並且它仍然可以工作,因為所有測試都將在此隱式頂級套件上進行定義。)

it(name, fn)執行此操作:

創建一個名為name的測試,並使用回調fn 將其添加到當前正在定義的套件中。

如果您仔細觀察代碼在運行時的狀況,就會發現運行after的代碼中,“當前正在定義的套件”是Mocha默認創建的包含所有測試的頂級隱式套件。 (它沒有名稱。如果將after(function () { console.log("after overall loop"); })到頂層describe ,您將看到所有inner test輸出均在after overall loop出現輸出。)

因此,您的after鈎向頂層隱式套件中添加了新測試。 它們必須在所有測試之后運行,因為它們是在套件末尾添加的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM