Before vs beforeEach in JavaScript: Key Differences Explained

before is a single hook that runs once, right before any test; beforeEach is a hook that runs before every single test case.

Devs often copy-paste suites and forget which hook they left behind, causing setup that should run once to silently repeat—or the opposite—leading to flaky, slow tests that only break on CI when the order matters.

Key Differences

before executes its callback once per describe block, ideal for heavy, shared setup like starting a server. beforeEach fires before every it(), guaranteeing a fresh fixture state, perfect for database rollbacks or resetting mocks.

Which One Should You Choose?

If the setup is expensive and immutable, use before. If each test needs isolation, use beforeEach. Mixing them without thought leaks state and breeds heisenbugs.

Examples and Daily Life

Launching a test database once: before. Clearing tables and seeding users before every route test: beforeEach. One keeps the coffee pot on all morning, the other washes your mug every refill.

Can I put async code in both hooks?

Yes, Jest and Mocha await returned promises, so `await db.connect()` works in either.

Will beforeEach run if before throws?

No, if a before hook fails, the whole suite is skipped; beforeEach never gets the chance.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *