Mocha的before()函数的目的是什么? [英] What is the purpose of Mocha's before() function?

查看:193
本文介绍了Mocha的before()函数的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Mocha有几个钩子可以在与测试用例本身分开的测试中运行辅助功能(清理数据库,创建模拟文件等)。



但是,在之前() beforeEach(),我得到的那个),这看起来很多余。



before()在当前所有测试之前运行逻辑一次套件,为什么我甚至需要将它包装在函数中?



以下两者之间没有可观察到的差异:

  describe('Something',function(){
before(doSomePreTestLogic);
//测试啊
});

  describe('Something',function(){
doSomePreTestLogic();
//测试啊!
});

在()之前用包装我的预测试逻辑有什么意义? / code>?

解决方案

为什么你可能会选择之前有几个不同的原因()在测试中挂钩:



语义



<这可能是最大的一个。有时您可能需要在运行实际测试之前执行任务,例如在数据库中填充一些虚拟数据。您当然可以在测试本身中执行此操作,但如果您在预填充时遇到错误,并且在运行实际测试用例之前,则会抛弃您的报告。通过在()
钩子之前有一个,你有一个逻辑的,语义上有效的位置来插入这种逻辑。



清除异步测试



就像mocha测试可以异步一样,你的也可以()钩子逻辑。回到预填充示例,这很方便,因为这意味着所有异步预测试逻辑都不会对所有实际测试逻辑强制进行另一级别的缩进。



与其他钩子的一致性:



Mocha还提供了其他几个钩子,即: after() beforeEach(),以及 afterEach()。你可能也会问同样的问题关于所有这些其他钩子,但如果你认为它们中的任何一个都有一个有效的存在,那么之前()真的需要包括在内以完善API。


Mocha has several 'hooks' to run assistive functionality in a test separate from the test cases themselves (clearing databases, creating mock files, etc).

However, in the case of before() (not beforeEach(), that one I get), it seems pretty redundant.

before() runs the logic once before all of the tests in the current suite, so why do I need to even wrap it in a function?

There's no observable difference between the two following:

describe('Something', function() {
    before(doSomePreTestLogic);
    //Tests ahoy
});

and

describe('Something', function() {
    doSomePreTestLogic();
    //Tests ahoy
});

What's the point of wrapping my pre-test logic with before()?

解决方案

There's a couple different reasons why you might opt for the before() hook in your tests:

Semantics

This is probably the biggest one. Sometimes you may need to perform a task, such as populate some dummy data in your database, prior to running an actual test. You can certainly do that in the test itself, but that throws off your reporting if you encounter an error while pre-populating, and before having run the actual test case at all. By having a before() hook, you have a logical, semantically valid place to insert this kind of logic.

Cleaner for Async Tests

Just like mocha tests can be asynchronous, so can your before() hook logic. Going back to the pre-population example, this is handy since that means all of your async pre-test logic won't force another level of indentation on all of your actual testing logic.

Consistency with other hooks:

Mocha also provides several other hooks, namely: after(), beforeEach(), and afterEach(). You could probably ask this same question about all these other hooks as well, but if you buy into the notion that any of them have a validated existence, then before() really needs to be included to round out the API.

这篇关于Mocha的before()函数的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆