Mocha has several \'hooks\' to run assistive functionality in a test separate from the test cases themselves (clearing databases, creating mock files, etc).
However,
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.