JS Guide
HomeQuestionsSearchResources
Search

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

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstesting
PrevNext
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 teardown
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();
  });
});

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?