
Learn how Jest beforeEach() boosts test reliability by handling repeated setup, ensuring clean states, and simplifying JavaScript test maintenance.
Last Modified on: November 18, 2025
Jest beforeEach() helps streamline your workflow by eliminating the need to repeat the same setup logic across many test cases. When requirements change, you only need to update the setup in one place instead of modifying multiple tests individually, which makes maintenance faster and more reliable.
It also ensures consistency across your test suite by centralizing initialization, reducing the risk of subtle bugs caused by mismatched or outdated setup code. By keeping repeated setups out of individual tests, Jest beforeEach() maintains cleaner test files that are easier to navigate and understand.
What Is Jest beforeEach()?
The Jest beforeEach() runs prior to each test case, allowing developers to establish repeatable pre-test conditions. Its placement controls which tests receive that setup, ensuring cleaner and more maintainable test files.
What Are the Steps to Use Jest beforeEach()?
Using beforeEach() in Jest helps you prepare a consistent environment before each test runs by handling repeated setup tasks automatically. After configuring Jest in your project, you can use this hook within test files or describe blocks to initialize data or reset components before every test executes.
What Are the Steps to Write Jest beforeEach() Tests?
Writing Jest beforeEach() tests involves preparing a module to test and using the hook to reset shared state before every test. By isolating setup logic, each test runs independently and avoids state carried over from previous executions.
The beforeEach() function is a Jest lifecycle hook that executes setup code before each individual test case runs. It ensures every test starts with a clean, predictable state by initializing variables, creating mock objects, or setting up test fixtures.
Jest provides several lifecycle hooks for setup and teardown, and beforeEach() specifically handles pre-test initialization, running once before every test() or it() block within its scope. This eliminates redundant setup code and maintains test isolation.

Note: Run JavaScript tests at scale across 3000+ browsers and OS combinations.. Try LambdaTest Today!
Using Jest beforeEach() involves placing your setup logic inside a callback that runs automatically before every test in the same scope. This helps ensure each test begins with a clean, consistent state. Simply define beforeEach() inside a test file or describe block, and Jest handles the rest.
Before you begin working with Jest or any Node-based tools, you need to ensure your system is properly set up with Node.js and npm. This setup provides the foundation for managing packages, running scripts, and creating a well-structured project. Once your environment is ready, you can create and initialize your project folder.
node -vnpm -v /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"With your project folder created, initialize it as a Node.js project to properly manage project dependencies.
After initializing your project, the next step is to install and configure Jest as your testing framework. This ensures your project can run automated tests smoothly and consistently.
With Jest installed, you need to configure it so you can easily run your tests with a simple command.
{
"name": "jest-beforeeach-demo",
"version": "1.0.0",
"type": "commonjs",
"scripts": {
"test": "jest"
},
"devDependencies": {
"jest": "^29.7.0",
"selenium-webdriver": "^4.38.0"
}
}Now that your project is fully set up with Jest, the next step is to create the module you want to test. Once the module is ready, you’ll write your first tests using Jest beforeEach() to handle initialization and shared setup for your tests.
Before writing Jest beforeEach() tests, you need to create a module to test. To do so, create a simple Calculator class that will serve as your test subject.
Create a new file named calculator.js inside your project folder and add the following code:
class Calculator {
constructor() {
this.result = 0;
}
add(num) {
this.result += num;
return this.result;
}
subtract(num) {
this.result -= num;
return this.result;
}
multiply(num) {
this.result *= num;
return this.result;
}
reset() {
this.result = 0;
}
getResult() {
return this.result;
}
}
module.exports = Calculator;

This simple Calculator class provides basic arithmetic operations that we'll test using Jest and beforeEach().
To write tests for your Calculator module, you need to create a dedicated test file.
Before writing tests that use the Jest beforeEach() hook, you first need to create a test file that Jest can detect and run. Jest automatically looks for files ending in .test.js, so creating one ensures your tests are properly recognized.
To do this, create a new file named calculator.test.js inside your project folder and add the following code:
const Calculator = require("./calculator");
describe("Calculator Tests", () => {
let calculator;
beforeEach(() => {
calculator = new Calculator();
});
test("should add numbers correctly", () => {
calculator.add(5);
calculator.add(3);
expect(calculator.getResult()).toBe(8);
});
test("should subtract numbers correctly", () => {
calculator.add(10);
calculator.subtract(4);
expect(calculator.getResult()).toBe(6);
});
test("should multiply numbers correctly", () => {
calculator.add(5);
calculator.multiply(3);
expect(calculator.getResult()).toBe(15);
});
test("should start with zero result", () => {
expect(calculator.getResult()).toBe(0);
});
});
Code Walkthrough:
The Jest beforeEach() creates a fresh Calculator instance before each test runs, ensuring every test starts with a clean state. Without the Jest beforeEach(), you would need to manually instantiate the Calculator in every test, which leads to unnecessary code duplication.
Each test begins with a clean calculator object where the result is reset to zero, making every outcome predictable and easier to validate. The hook runs once before each of the four test cases in this suite, ensuring consistent initialization across all tests.
Run the Tests:
Run the following command:
npm testOnce the tests run, Jest will discover the test file, execute the beforeEach() hook in Jest before each test, and display the results in your terminal.

Running beforeEach() before every test can slow down large test suites that involve a complex setup. Local environments may also lack sufficient memory or CPU to efficiently handle heavy initialization for many tests.
Additionally, differences in local machine configurations can sometimes lead to unexpected failures. When multiple beforeEach() hooks or nested describe blocks are used, tracing issues can become more challenging and time-consuming.
Using cloud environments can help overcome these issues. They allow tests to run in parallel, provide standardized environments across machines, and allocate extra CPU, memory, and storage for heavier suites. Test results are consolidated, making monitoring and debugging easier. One such cloud environment is LambdaTest.
LambdaTest is a cloud testing platform that allows you to perform manual and automated Jest testing at scale across 3,000+ browser and OS combinations.
To get started with the LambdaTest platform and implement beforeEach() in Jest, we will use the LambdaTest eCommerce Playground website for demonstration purposes.
npm install --save-dev selenium-webdriverconst capabilities = {
browserName: "Chrome",
browserVersion: "latest",
"LT:Options": {
username: process.env.LT_USERNAME,
accessKey: process.env.LT_ACCESS_KEY,
platformName: "Windows 10",
project: "Jest beforeEach Demo",
build: "eCommerce Tests",
name: "Product Search Test",
w3c: true,
plugin: "node_js-jest",
},
};You can generate the necessary capabilities using the LambdaTest Automation Capabilities Generator.
const gridURL = "https://" + process.env.LT_USERNAME + ":" + process.env.LT_ACCESS_KEY + "@hub.lambdatest.com/wd/hub";Run the Tests:
Run the following command:
npm testOnce the tests start, the beforeEach() hook creates a new browser session for each test, runs the test logic, and the afterEach() hook closes the session. You'll see the test results displayed in your terminal.
Output:

Result:
After your tests are complete, you can review the results on LambdaTest Dashboard > Web Automation.

On the LambdaTest result, you can view detailed test session views that provide logs, video playback, and session metadata.
To get started, follow this support documentation on Jest with Selenium to configure and run your JavaScript automation testing scripts.
Jest beforeEach() helps keep your tests clean, consistent, and predictable by resetting state before every test. It prevents test interference, reduces duplication, and improves maintainability in larger test suites.
The Jest beforeEach() hook is a fundamental part of writing clean and maintainable test suites, especially as your project grows. Understanding how it initializes state before every test will make your testing workflow far more reliable and structured.
To explore this concept in-depth and continue building strong testing skills, you can learn more from the official Jest tutorial.
In more complex test suites, JavaScript automation testing with Jest often requires a shared setup for all tests as well as group-specific configurations.
Jest allows you to nest describe() blocks and use multiple beforeEach() hooks to achieve this hierarchy, ensuring a clean and maintainable structure.
Jest beforeEach() works well for simple tests to keep setup organized. However, for more complex test suites, you can use nested describe() blocks with multiple Jest beforeEach() hooks to structure your tests more effectively.
Before writing nested tests, it’s important to understand how Jest executes multiple levels of describe() blocks and Jest beforeEach() hooks.
When several tests share a common setup but also require group-specific initialization, nested describe() blocks with multiple Jest beforeEach() hooks are the ideal solution:
This structure ensures each test starts with a consistent base state while allowing flexible, group-specific configuration.
To demonstrate nested Jest beforeEach() behavior, you'll need a new test file.
Let's create a test file that demonstrates how Jest beforeEach() works with nested describe() blocks. Create a new file named nested-beforeeach.test.js inside your project folder and paste the following code:
const Calculator = require("./calculator");
describe("Calculator", () => {
let calculator;
beforeEach(() => {
console.log("Outer beforeEach: Creating calculator");
calculator = new Calculator();
});
test("should initialize with zero", () => {
expect(calculator.getResult()).toBe(0);
});
describe("Addition Operations", () => {
beforeEach(() => {
console.log("Inner beforeEach: Setting up for addition");
calculator.add(10);
});
test("should add positive numbers", () => {
calculator.add(5);
expect(calculator.getResult()).toBe(15);
});
test("should add negative numbers", () => {
calculator.add(-3);
expect(calculator.getResult()).toBe(7);
});
});
describe("Multiplication Operations", () => {
beforeEach(() => {
console.log("Inner beforeEach: Setting up for multiplication");
calculator.add(5);
});
test("should multiply by positive number", () => {
calculator.multiply(3);
expect(calculator.getResult()).toBe(15);
});
test("should multiply by zero", () => {
calculator.multiply(0);
expect(calculator.getResult()).toBe(0);
});
});
});
Code Walkthrough:
Run the Tests:
Run the following command:
npm test nested-beforeeach.test.jsThis command runs only the nested tests file. You'll see console output showing the execution order of the Jest beforeEach() hooks, demonstrating how the outer hook runs before each inner hook.

Benefits of Nested Jest beforeEach()
After seeing nested Jest beforeEach() in action, let's understand why this pattern is valuable.
This pattern provides several advantages:
Use outer beforeEach() for setup shared across all tests, and use inner beforeEach() in nested describe blocks for setup specific to each test group. This creates clean and maintainable test suites that are easy to understand and extend.
The beforeEach() hook is particularly useful for managing mocks, spies, and global state that needs resetting between tests. This ensures each test runs with clean mock data and prevents test pollution.
The use of Jest beforeEach() here is to manage complex test scenarios involving mocked APIs, spied functions, and global state that needs to be reset between tests.
To demonstrate mock management, you'll need a test file that simulates API calls. To do that, create a new file named api-service.test.js inside your project folder and paste the code below:
// Mock axios without importing it
const axios = {
get: jest.fn(),
post: jest.fn(),
put: jest.fn(),
delete: jest.fn(),
};
describe("API Service Tests", () => {
let mockData;
beforeEach(() => {
mockData = {
users: [
{ id: 1, name: "John Doe", email: "john@example.com" },
{ id: 2, name: "Jane Smith", email: "jane@example.com" },
],
};
jest.clearAllMocks();
});
test("should fetch users successfully", async () => {
axios.get.mockResolvedValue({ data: mockData.users });
const response = await axios.get("/api/users");
expect(axios.get).toHaveBeenCalledWith("/api/users");
expect(response.data).toEqual(mockData.users);
expect(response.data.length).toBe(2);
});
test("should handle API errors", async () => {
const errorMessage = "Network Error";
axios.get.mockRejectedValue(new Error(errorMessage));
await expect(axios.get("/api/users")).rejects.toThrow(errorMessage);
expect(axios.get).toHaveBeenCalledWith("/api/users");
});
});Code Walkthrough
Using jest.clearAllMocks() and jest.restoreAllMocks() in beforeEach() guarantees predictable, isolated test behavior across multiple tests.
The Jest beforeEach() hook helps manage Mockito spy effectively by allowing you to set up spies, which monitor function calls without altering their behavior.
To demonstrate spy management, you'll need a test file that monitors console output. Create a new file named logger-service.test.js inside your project folder and paste the following code:
describe("Logger Service Tests", () => {
let consoleLogSpy;
let consoleErrorSpy;
beforeEach(() => {
consoleLogSpy = jest.spyOn(console, "log").mockImplementation();
consoleErrorSpy = jest.spyOn(console, "error").mockImplementation();
});
afterEach(() => {
consoleLogSpy.mockRestore();
consoleErrorSpy.mockRestore();
});
test("should log info messages", () => {
const logger = { info: (msg) => console.log(`INFO: ${msg}`) };
logger.info("Test message");
expect(consoleLogSpy).toHaveBeenCalledWith("INFO: Test message");
expect(consoleLogSpy).toHaveBeenCalledTimes(1);
});
test("should log error messages", () => {
const logger = { error: (msg) => console.error(`ERROR: ${msg}`) };
logger.error("Test error");
expect(consoleErrorSpy).toHaveBeenCalledWith("ERROR: Test error");
expect(consoleErrorSpy).toHaveBeenCalledTimes(1);
});
});Code Walkthrough:
This pattern is essential for testing code that logs to the console, writes to files, or calls monitored functions without changing behavior.
You've now learned all the core techniques for using beforeEach() in various scenarios. Let's consolidate this knowledge with best practices that will help you write cleaner, more maintainable test suites.
Following established patterns when using beforeEach() creates maintainable and reliable test suites. These practices help avoid common pitfalls and improve test clarity.
Important: Jest tests should avoid real file I/O, database connections, or network calls in beforeEach(), use mocks or test doubles instead to keep tests fast and isolated.
beforeEach(() => {
jest.clearAllMocks(); // Most common: reset tracking, keep behavior
});Using the appropriate reset method prevents mock behavior from leaking between tests, making each test independent and reducing unexpected failures.
The Jest beforeEach() function in Jest provides a powerful mechanism for test initialization, reducing code duplication and ensuring consistent test setup. This article covered the fundamental concepts of Jest beforeEach(), from basic usage to advanced scenarios involving nested describe blocks and mock management.
You learned how to implement Jest beforeEach() in local test environments and scale testing across browsers using cloud Selenium grids. The function's scope-based behavior allows flexible setup inheritance, while its integration with mocks and spies enables clean test isolation.
By following the best practices outlined, you can create maintainable test suites that run reliably across different environments. The Jest beforeEach() hook is an extremely useful method for writing clean, organized Jest tests that execute predictably and fail clearly when issues arise.
Did you find this page helpful?
More Related Hubs
Start your journey with LambdaTest
Get 100 minutes of automation test minutes FREE!!