Master Jest's beforeEach to Simplify Repetitive Test Setup

Learn how the Jest beforeEach function works to simplify repetitive test setup and enhance your testing workflow.

Get Started free
Home Guide Understanding Jest beforeEach Function

Understanding Jest beforeEach Function

By Antra Verma, Community Contributor -

Jest is a popular JavaScript testing framework, widely used for unit testing in modern web development projects. It integrates smoothly with JavaScript libraries such as React, Angular, and Node.js, making it a favored choice among developers.

This article explores Jest’s beforeEach() function, its purpose, and how it fits into a typical Jest testing workflow.

What is Jest beforeEach()?

The beforeEach() function in Jest allows you to run a setup operation before each individual test in a suite. This function is crucial for maintaining test independence and ensuring that each test runs in a clean environment, preventing side effects from impacting test outcomes.

Syntax:

beforeEach(() => {

  // setup logic before each test

});

The primary reason for using beforeEach() is to avoid duplication in a test setup. Instead of repeating the same initialization code in multiple tests, you can use beforeEach() to ensure the setup logic is run before each test. This simplifies the code, improves readability, and ensures consistency across tests.

Setting up specific conditions before every test also ensures that no test is dependent on the outcome of another. In essence, it isolates tests and helps maintain their independence.

Prerequisites: (Project Setup & Jest Installation)

Follow these steps to set up a basic Node.js project with jest before diving deeper into the beforeEach() function.

1. Initialize a Node.js project:

First, create a new directory for your project and initialize it:

mkdir jest-test-app

cd jest-test-app

npm init -y

This will create a package.json file with default settings.

{

  "name": "jest-test-app",

  "version": "1.0.0",

  "main": "index.js",

  "scripts": {

    "test": "echo \"Error: no test specified\" && exit 1"

  },

  "keywords": [],

  "author": "",

  "license": "ISC",

  "description": ""

}

2. Install Jest

Install Jest as a development dependency:

npm install jest --save-dev

3. Set up Jest in package.json

Modify the package.json file to add a test script. Add the following to the “scripts” section:

"scripts": {

…….

  "test": "jest"

………..

}

This allows you to run Jest tests with the npm test command.

Read More: Configuring Jest

How does beforeEach() work with Multiple Tests?

When using beforeEach(), it runs before every test in the suite. For instance, in a test file containing multiple tests, the beforeEach() block will execute each time before a test is run.

Example:

//tests/example.test.js



beforeEach(() => {

  console.log("Running setup before each test");

});



test('test one', () => {

  console.log("Test one executed");

});



test('test two', () => {

  console.log("Test two executed");

});

Output:

Running setup before each test

Executing the beforeEach() function Before Every Test

Jest automatically executes the beforeEach() function before running each test. This ensures that any setup required for the tests is executed beforehand, providing a consistent test environment.

For example, if you’re testing functions that rely on external dependencies or specific data structures, you can initialize them in beforeEach():

let arr;



beforeEach(() => {

  arr = [1, 2, 3];

});



test('should add an item to the array', () => {

  arr.push(4);

  expect(arr).toEqual([1, 2, 3, 4]);

});



test('should not change array length initially', () => {

  expect(arr.length).toBe(3);

});

Output:
Pass Example.js

Understanding Order and Sequence of Execution

The beforeEach() function always runs before each test, ensuring a predictable order of execution. Jest also offers other functions like afterEach(), which runs after every test, and beforeAll(), which runs once before all tests in a suite.

When using beforeEach() with beforeAll() and afterEach(), the order of execution is as follows:

  1. beforeAll()
  2. beforeEach()
  3. Test execution
  4. afterEach()
describe('Order and Sequence of Execution', () => {

  

  beforeAll(() => {

    console.log('1 - beforeAll');

  });



  beforeEach(() => {

    console.log('2 - beforeEach');

  });



  test('First test case', () => {

    console.log('3 - First test case');

  });



  test('Second test case', () => {

    console.log('3 - Second test case');

  });



  afterEach(() => {

    console.log('4 - afterEach');

  });



  afterAll(() => {

    console.log('5 - afterAll');

  });



});

Output:

Jest example tests execution for multiple functions

Using beforeEach() with describe()

Jest allows you to group tests using the describe() function. When beforeEach() is used within a describe() block, it runs before each test inside that block.

Grouping Tests with describe()

describe() allows you to logically group related tests. Each describe() block can have its own beforeEach() function, which will only run for tests inside that specific block.

describe('String Operations', () => {

  let str;



  beforeEach(() => {

    // Reset the string before each test

    str = 'Hello';

  });



  test('should start with "Hello"', () => {

    expect(str).toBe('Hello');

  });



  test('should add " World" to the string', () => {

    str += ' World';

    expect(str).toBe('Hello World');

  });

});

Output:

Execute example.test .js for Hello World

Running Setup Before Each Test in the Group

When you place beforeEach() inside a describe() block, it will only apply to the tests within that block. This helps structure tests that require distinct setups.

Each describe() block can have its own beforeEach() function. If multiple describe() blocks are present, each beforeEach() within a block will only apply to the tests inside that specific block. This allows for a modular and structured approach to testing. Within each describe() block, the beforeEach() is executed before each individual test runs, ensuring a clean slate for every test within that group.

Example Use Case of Jest beforeEach()

Create a simple user management module that you must test:

// src/userManager.js

class UserManager {

  constructor() {

    this.users = [];

  }



  addUser(user) {

    this.users.push(user);

  }



  removeUser(user) {

    this.users = this.users.filter(u => u !== user);

  }



  getUsers() {

    return this.users;

  }

}



module.exports = UserManager;

Next, write tests for this module using Jest. Use beforeEach() to ensure that you start with a fresh instance of UserManager and an empty user list before each test run.

// tests/userManager.test.js

const UserManager = require('../src/userManager');



describe('UserManager', () => {

  let userManager;



  beforeEach(() => {

    // Create a new instance of UserManager before each test

    userManager = new UserManager();

  });



  test('should start with an empty user list', () => {

    expect(userManager.getUsers()).toEqual([]);

  });



  test('should add a user to the user list', () => {

    userManager.addUser('Alice');

    expect(userManager.getUsers()).toEqual(['Alice']);

  });



  test('should remove a user from the user list', () => {

    userManager.addUser('Bob');

    userManager.removeUser('Bob');

    expect(userManager.getUsers()).toEqual([]);

  });



  test('should not remove a user that does not exist', () => {

    userManager.addUser('Charlie');

    userManager.removeUser('David'); // David does not exist

    expect(userManager.getUsers()).toEqual(['Charlie']);

  });



  test('should add multiple users', () => {

    userManager.addUser('Eve');

    userManager.addUser('Mallory');

    expect(userManager.getUsers()).toEqual(['Eve', 'Mallory']);

  });

});

Output:

Execute usermanager.test .js

Benefits of using Jest beforeEach()

The beforeEach() function in Jest offers several significant benefits, especially improving the clarity, maintainability, and scalability of your test suites. Some of its main advantages are given below:

  • Code Reusability:
    Instead of repeating the same initialization code in every test, beforeEach() allows you to reuse setup logic across multiple tests. This keeps your test code DRY (Don’t Repeat Yourself), making it more concise and readable.
    For Example, If all your tests need a mock database connection or an initialized array, beforeEach() can set this up once for all tests, avoiding redundancy.
  • Test Isolation:
    Test isolation is crucial for maintaining the accuracy of test results. By running the beforeEach() setup function before every test, you ensure that each test starts with the same clean, predefined environment. This prevents side effects from other tests from influencing the outcome.
  • Readability:
    beforeEach() helps structure your tests in a way that separates setup code from actual test logic. This separation makes the tests easier to understand and maintain because it keeps test logic focused on what you’re testing rather than how the environment is set up.
  • Facilitates Complex Setup Logic:
    In some scenarios, test environments require complex or time-consuming setups, such as creating temporary files, initializing services, or resetting databases.
    beforeEach() enables you to handle this efficiently by executing the setup logic before every test, ensuring that these conditions are met consistently.
  • Compatibility with Mocking and Spying:
    beforeEach() can be integrated with Jest’s powerful mocking and spying utilities. It ensures that mocks or spies are reset and recreated before each test, maintaining test independence.
    For example, if you mock API requests or spy on function calls, beforeEach() ensures that the mock state is refreshed for each test.
  • Eases Transition to TDD (Test-Driven Development):
    For teams practicing Test-Driven Development (TDD), where tests are written before the actual code, beforeEach() offers a clean and predictable way to set up initial conditions for each test.
    This enables developers to focus on writing meaningful tests while keeping setup logic streamlined.

Talk to an Expert

Best Practices while using Jest beforeEach()

To fully leverage the power of beforeEach() while keeping your test suites optimized, it’s important to follow certain best practices. Below are some key recommendations to keep in mind:

1. Keep Setup Logic Minimal and Relevant

Only include essential setup code that directly impacts the tests. Avoid complex or unnecessary setup logic that can slow down tests or obscure test purposes.

2. Use beforeEach() for State Reset

Use beforeEach() to reset mutable state (e.g., variables, mocks) before each test. If a setup doesn’t change across tests, consider beforeAll() to run the setup only once for improved performance.

3. Avoid Heavy Setup Operations

Keep resource-intensive operations (like database connections) out of beforeEach(). Instead, mock expensive operations or move them to beforeAll() to reduce test overhead.

4. Mock External Dependencies

Reset or mock external APIs or functions in beforeEach() to maintain test isolation and ensure clean test environments for every run.

5. Handle Asynchronous Setup Properly

For async setup, use async/await in beforeEach(), ensuring that all setup tasks are complete before the test starts. Handle potential promise rejections to prevent flaky tests.

6. Scope Setup to Test Groups

Define beforeEach() inside describe() blocks to apply it specifically to tests in that group, maintaining modular and organized test logic.

7. Pair with afterEach() for Cleanup

Use afterEach() alongside beforeEach() to clean up resources (e.g., closing files, clearing mocks) after each test to avoid any leftover state affecting subsequent tests.

Why choose BrowserStack to run Selenium Jest tests?

Running Jest tests on BrowserStack Automate ensures your code works seamlessly across real devices and browsers. Here are the reasons why you must choose BrowserStack to run Selenium Jest tests:

BrowserStack Automate Banner

  • Automated Tests: Integrate Jest with BrowserStack’s real devices for automated, end-to-end testing.
  • Selenium Grid: Leverage Selenium Grid to run tests in parallel across multiple browsers and devices.
  • CI/CD Integration: BrowserStack integrates with your CI/CD pipelines, ensuring smooth automated testing with tools like Jenkins and CircleCI.
  • No Maintenance: Access a cloud-based infrastructure without the hassle of managing device labs or virtual machines.
  • Cross-Browser Testing: Ensure your application works across different browser versions and operating systems, improving cross-browser compatibility.
  • Real-Time Debugging: Debug test failures quickly with real-time logs, screenshots, and video recordings, making troubleshooting much easier.
  • Scalability: Easily scale your test suite across thousands of devices and browsers simultaneously, speeding up test execution and reducing bottlenecks.

Using BrowserStack, you can ensure your Jest tests cover a wide range of environments without the hassle of managing physical devices or multiple configurations.

Conclusion

The beforeEach() function in Jest is a vital tool for streamlining your test setup, ensuring consistency, and isolating tests. By incorporating it into your testing workflow, you can write cleaner, more maintainable tests.

Combine Jest with BrowserStack Automates’s testing infrastructure to enhance your test coverage, improve speed, and ensure seamless integration into your development pipelines.

Try BrowserStack Now

Tags
Automation Testing Selenium Website Testing

Featured Articles

Jest vs Mocha vs Jasmine: Which JavaScript framework to choose?

How to Configure Jest

Scale Your Jest Testing

Run your Jest tests across real devices and browsers with BrowserStack Automate, ensuring reliable results and faster testing cycles.