In the Mocha Test Framework, when should we use the before() hook instead of the beforeEach() hook?

In the context of the exercise from the Full-Stack Engineer Path in the TDD/Write Good Tests With Mocha sub-module Exercise, why are we using the before() hook and not the beforeEach() hook?

Because from Mocha’s official documentation, it makes more sense to use the beforeEach() hook, as we want it to set the same value in the setup phase for all tests inside a test group. In the exercise, however, we are prompted to use the before() hook, which, according to the Mocha documentation, is called once, before the first test in the group.

You can use both of these. before/after is called once per group so I have used it for things like creating/deleting db tables to test against. beforeEach runs before every test so it is useful so set up tests in a more isolated way. But it is not always necessary to put everything in beforeEach which would make tests slower. The particular thing you are testing will help determine the right one to use.

1 Like

Thank you very much for the clarification!