JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstesting
PrevNext

Learn the concept

Test Lifecycle Hooks

testing
junior
setup

How do you use beforeEach, afterEach, beforeAll, and afterAll in Jest?

jest
setup
teardown
lifecycle
beforeEach
Quick Answer

These are Jest lifecycle hooks for test setup and cleanup. beforeEach/afterEach run before/after each test. beforeAll/afterAll run once before/after all tests in a describe block. Use them to set up test data, mock functions, or clean up resources.

Detailed Explanation

Lifecycle Hooks:

  • beforeAll(): Once before all tests in block
  • afterAll(): Once after all tests complete
  • beforeEach(): Before every test
  • afterEach(): After every test

Common Use Cases:

beforeEach:

  • Reset mocks
  • Set up test data
  • Initialize component

afterEach:

  • Clean up DOM
  • Clear mocks
  • Reset state

beforeAll:

  • Database connection
  • Start server
  • Expensive setup

afterAll:

  • Close connections
  • Clean up test database
  • Stop servers

Code Examples

Basic setup and teardownJavaScript
describe('User service', () => {
  let userService;
  let mockDatabase;

  // Run once before all tests
  beforeAll(() => {
    console.log('Setting up test suite');
    mockDatabase = createMockDatabase();
  });

  // Run before each test
  beforeEach(() => {
    userService = new UserService(mockDatabase);
    // Reset any mock state
    jest.clearAllMocks();
  });

  // Run after each test
  afterEach(() => {
    // Clean up any side effects
    userService = null;
  });

  // Run once after all tests
  afterAll(() => {
    console.log('Cleaning up test suite');
    mockDatabase.close();
  });

  test('creates user', () => {
    const user = userService.create({ name: 'Alice' });
    expect(user).toHaveProperty('id');
  });

  test('finds user by id', () => {
    const user = userService.findById(1);
    expect(user).toBeDefined();
  });
});

Real-World Applications

Use Cases

Setting up a clean slate for each unit test in a component, ensuring test isolation

Using `beforeEach` to re-initialize the component, reset mock states, or clear any global side effects before each test runs, preventing tests from impacting each other and ensuring consistent results.

Establishing a database connection or starting a mock server once for an entire test suite

Utilizing `beforeAll` to perform expensive setup operations only once at the beginning of the test file, and `afterAll` to tear down these resources, significantly speeding up the overall test execution time.

Cleaning up DOM elements or mock API responses after each component test

Employing `afterEach` to unmount React components, clear the JSDOM environment, or reset network mocks, ensuring that the test environment is pristine for the next test.

Mini Projects

Mocking API with Jest Setup

intermediate

Create a simple application that fetches data from a mock API. Use `beforeAll` to set up Jest's mock API and `afterAll` to clean it up, demonstrating efficient test setup and teardown.

Component Testing with beforeEach

beginner

Develop a small React component and write several tests for it. Use `beforeEach` to render the component anew before each test, ensuring each test operates on an isolated component instance.

Industry Examples

Stripe (Jest)

Stripe's engineering team uses Jest's setup/teardown hooks to manage complex test environments, such as mocking network requests for API clients or setting up isolated database states for integration tests, ensuring their payment infrastructure remains robust.

Airbnb (Jest)

Airbnb leverages these hooks for their extensive React component tests. `beforeEach` is commonly used to mount components in a clean JSDOM environment, while `afterEach` ensures proper unmounting and cleanup, critical for preventing memory leaks and test pollution in large-scale UI testing.

Resources

Jest Setup and Teardown

docs

Related Questions

How do you mock functions, modules, and API calls in Jest?

mid
mocking

What are the most commonly used Jest matchers?

junior
jest
Previous
What are the most commonly used Jest matchers?
Next
How do you test asynchronous code in Jest?
PrevNext