beforeAll, beforeEach, afterAll, afterEach — What Goes Where and Why It Matters in Testing

Shayan DanishShayan Danish
2 min read

When writing tests in Jest, Mocha, or any modern test runner, you’ve probably used these lifecycle hooks:

  • beforeAll()

  • beforeEach()

  • afterAll()

  • afterEach()

But what happens when you place them outside vs inside a describe() block?
Let’s break it down.


🧪 The Four Hooks, Quickly Explained

HookRuns...
beforeAllOnce before all tests in a file or describe() block
beforeEachBefore every test case
afterEachAfter every test case
afterAllOnce after all tests in a file or describe() block

🧭 Where You Place Them Matters

Placed outside of describe():

beforeAll(() => connectDB());
afterAll(() => disconnectDB());

➡️ Applies to all test cases in the file, across multiple describe() blocks.

Use this when:

  • You want to connect DB once and reuse it

  • You want global setup/teardown


Placed inside a describe():

describe('Auth Routes', () => {
  beforeEach(() => resetAuthMocks());
  afterEach(() => clearAuthMocks());

  test('should login', () => { /*...*/ });
});

➡️ Applies only to tests within that describe block.

Use this when:

  • You need scoped setup/reset logic

  • You have isolated state per test group


💡 Pro Tip: Combine Them Smartly

beforeAll(() => startServer()); // once for the file
afterAll(() => stopServer());

describe('User Routes', () => {
  beforeEach(() => seedUserData());
  afterEach(() => clearUserData());

  test('GET /users', () => {});
  test('POST /users', () => {});
});

describe('Auth Routes', () => {
  beforeEach(() => seedAuthData());
  afterEach(() => clearAuthData());

  test('POST /login', () => {});
});

🧨 Common Mistakes to Avoid

  • ❌ Using beforeEach() to connect DB (wastes time)

  • ❌ Forgetting afterAll() — leads to hanging tests

  • ❌ Global state leakage by skipping afterEach()


✅ Final Checklist

  • beforeAll → Global setup (DB/server start)

  • afterAll → Global cleanup (DB/server stop)

  • beforeEach → Local per-test reset (mock data)

  • afterEach → Cleanup after each test (clear mocks, cookies)


Use these wisely, and your tests will be faster, isolated, and reliable.

0
Subscribe to my newsletter

Read articles from Shayan Danish directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shayan Danish
Shayan Danish

Full Stack Developer | Building Products & Crafting Solutions for Everyday Challenges