如何正确地将测试套件放在摩卡的函数中

How to correctly put test suites in functions in mocha?

本文关键字:摩卡 函数 套件 正确地 测试      更新时间:2023-09-26

我对摩卡相当陌生,整个夏天我一直在使用它,为 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 创建该套件以包含所有测试。(因此,您可能有一个根本不使用describe的测试文件,它仍然可以工作,因为所有测试都将在此隐式顶级套件上定义。

it(name, fn)这样做:

创建名为 name 并使用回调fn的测试。将其添加到当前正在定义的套件中。

如果你在心里跟踪代码运行时发生了什么,你会发现当after中的代码运行时,"当前正在定义的套件"是 Mocha 默认创建的顶级隐式套件,用于包含所有测试。(它没有名字。如果将after(function () { console.log("after overall loop"); })添加到顶级describe ,您将看到所有inner test输出都显示在after overall loop输出之后。

因此,您的after钩子正在向顶级隐式套件添加新测试。它们必须在所有测试之后运行,因为它们是在套件末尾添加的。