如何正确地将测试套件放在摩卡的函数中
How to correctly put test suites in functions in 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
钩子内部调用describe
和it
。它不会使测试套件崩溃,但它不是 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
钩子正在向顶级隐式套件添加新测试。它们必须在所有测试之后运行,因为它们是在套件末尾添加的。
- 摩卡由于绝对路径而不断轰炸
- 如何使用浏览器中用酶创建的组件反应例如摩卡
- 找不到模块'它'当用摩卡/柴测试时
- 摩卡+柴+jsdom Can't加载自定义模块目录
- 如何将 XML 文件包含在摩卡测试用例中
- 摩卡与敏捷(异步)冲突
- 用于摩卡测试的 CLI 调试器
- 如何在摩卡测试中使用“定义”
- 摩卡“每个钩子之前”红色消息.我怎么知道具体出了什么问题
- 错误:使用摩卡测试时找不到模块
- 大口喝摩卡如何传递编译器标志
- 我可以从摩卡测试MarkLogic SJS吗
- 用摩卡测试失败的承诺'内置的promise支持
- 在摩卡中使用请求调用测试函数
- 使用摩卡在节点上测试错误.js函数
- 测试使用摩卡在其中调用承诺的函数
- 摩卡如何公开节点控制器函数来测试脚本
- 摩卡的 before() 函数的目的是什么
- 在摩卡失败的“断言”中;In assert函数导致超时而不是失败
- 如何正确地将测试套件放在摩卡的函数中