NodeJS Testing Framework beforeEach() vs beforeAll()

I’ve been using the Jest testing framework in a side project. One of the areas I needed to test required that I populate data in my MongoDB database so that there was something for the tests to run against.

I had some debate in my mind between using beforeEach(), which does the database population step before each individual test is executed (once for each test), or using beforeAll(), which does the database population step one time before the tests are run collectively.

BeforeAll() seemed like the more efficient–and therefore quicker–way to do things because it would involve fewer calls to the database, but I ran into a circumstance where that was making writing a couple of the tests more difficult.

In testing however, I found that there wasn’t any consistent difference in speed between using beforeEach() and using beforeAll(). I don’t know if that’s because Jest is running the tests asynchronously and therefore the wait while the database is populated is mostly overlapping for each of the tests, or if Jest is doing something where it doesn’t actually run the beforeEach on tests that don’t read from the database, or if there is something else entirely going on there.

The key takeaway for me was that it didn’t matter (from a performance standpoint) whether I used beforeEach() or beforeAll(). As a result, I’ll be using beforeEach() because it makes writing tests slightly easier.

Leave a Reply