पाठ 6 / 25

Setup, Teardown and Test Isolation

beforeEach, afterEach and why order must not matter.

Every test starts from a clean slate

beforeEach / afterEach run around every test in their describe block; beforeAll / afterAll run once per block. Use them for shared setup and cleanup, such as resetting an in-memory store, clearing mocks or restoring timers. The rule behind them is isolation: each test must pass on its own and in any order, because runners can filter, shuffle (--sequence.shuffle in Vitest, --randomize in recent Jest) and run files in parallel workers. Shared mutable state at module level, leftover mocks and un-restored globals are the usual causes of tests that pass alone and fail together. Prefer creating fresh data inside the test or in beforeEach over sharing objects created in beforeAll.

Fresh state per test

A store reset before each test and mocks restored after.

import { beforeEach, afterEach, describe, it, expect, vi } from 'vitest';
import { createCartStore, type CartStore } from './cartStore';

describe('cart store', () => {
  let store: CartStore;

  beforeEach(() => {
    store = createCartStore();            // new instance: no leaks between tests
  });

  afterEach(() => {
    vi.restoreAllMocks();                 // undo spies created in a test
  });

  it('starts empty', () => {
    expect(store.items()).toEqual([]);
  });

  it('adds an item', () => {
    store.add({ sku: 'tea', qty: 2 });
    expect(store.items()).toHaveLength(1);
  });
});

// config alternative: let the runner reset mocks for you
// vitest.config.ts -> test: { restoreMocks: true }   jest.config.ts -> restoreMocks: true

Resetting the stage between scenes

A theatre crew resets every prop before the next scene so no actor trips over something left behind. beforeEach and afterEach are that crew.

त्वरित जाँच: A test passes alone but fails when the whole file runs. What is the most likely cause?

  • The file has too many describe blocks
  • The test name is too long
  • toEqual is slower than toBe
  • State leaking between tests, such as a shared object or an unrestored mock
Answer

State leaking between tests, such as a shared object or an unrestored mock — Tests must be independent of order.