如何在mocha中正确地将测试套件放入函数中?

时间:2016-07-17 15:32:55

标签: javascript node.js 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

我不明白为什么内心测试&#39;在结束时连续输出5次,而不是在测试后连续输出&#39;每一次。任何意见都非常感谢。

1 个答案:

答案 0 :(得分:0)

您的代码正在describe挂钩内调用itafter。它不会使测试套件崩溃,但它不是Mocha明确支持的使用模式。因此它没有按照您的预期执行。

您得到的结果是因为describe(name, fn)执行此操作:

  

创建名为name的测试套件。将其添加到当前正在定义的套件中。推动套件堆栈上的新套件。致电fn。弹出套件堆栈。

目前正在定义的&#34;套件&#34;是套件堆栈顶部的那个。摩卡维持着一揽子套房。它最初包含一个顶级隐式套件,Mocha创建它以包含所有测试。 (所以你可以有一个完全不使用describe的测试文件,它仍然可以工作,因为所有测试都将在这个隐含的顶级套件上定义。)

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

  

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

如果您在运行时对您的代码进行了精神上的跟踪,您会发现当after中的代码运行时,正在定义的&#34;套件&#34;是Mocha默认创建的包含所有测试的顶级隐式套件。 (它没有名称。如果您将after(function () { console.log("after overall loop"); })添加到顶级describe,则会在inner test输出后看到所有after overall loop输出。)

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