See Testim Copilot in action | Join us

Mocha beforeEach Explained With a Side-by-Side Comparison

Sometimes, while writing tests with tools like Mocha, you may want to perform certain operations before the tests. These operations…

Testim
By Testim,

Sometimes, while writing tests with tools like Mocha, you may want to perform certain operations before the tests. These operations might include the initial setup of global services or resources and configuration for the tests. Mocha’s beforeEach method makes these test setups easier and reduces code duplication.

Mocha has several hooks, including before, after, beforeEach, and afterEach. They make it possible to intercept tests before or after the test run and to perform specific tasks. For example, the beforeEach hook intercepts your test right before each test in a suite is run.

This post will explain Mocha’s beforeEach and some essential things you should know about it.

What Is beforeEach?

The beforeEach method is a feature (hook) in test libraries that you can use to set preconditions for each test. Just like the name suggests, it runs before each test in your test suite. For example, the beforeEach method will run four times in a suite with four tests. Each execution will happen just before the actual test function.

Because of the nature of the beforeEach method, it’s great for doing initial setups such as generating mock data or configurations before each test, for example. Another name for beforeEach is “setup,” while its opposite companion, afterEach, is also called “tear down.”

Using beforeEach In Mocha

Now that you know what beforeEach is let’s look at how to use it in your Mocha tests.

In this example, we’ll write a test suite and simply log a message to the console to show that our beforeEach method executes.

describe("Tests with beforeEach", function () {
  beforeEach(function () {
    console.log("Initialising...");
  });

  it("Test1", function () {
    //write test logic here
  });

  it("Test2", function () {
    //write test logic here
  });
});

From the above code, we have a test suite and two tests. Also, our tests are empty, and hence they will always pass. When we run the test, we get the “Initialising” message on the console for each test. If you increase the number of tests to three, this message will be displayed three times.

When to Use beforeEach vs. When to Not Use beforeEach

Use beforeEach When

1. Running code that’s common to multiple tests. If you have code that performs the same operation in the tests in your test suite, you may want to move the code to beforeEach where it’s applicable.

2. Setting up configuration. Another good case for using beforeEach is to set configurations that are common to multiple tests.

3. Cleaning up the application state and resources. You can use the beforeEach method to reset the state of the application you’re testing before running each test in a suite. For example, you may clear old test data from the database using beforeEach. You may also use it to delete files generated by previous tests.

Don’t Use beforeEach When

1. Running code that’s not global or common to multiple tests. If you have various tests in your suite that don’t share a common service, you’re better off moving the initialization of each service to the test that needs it. Using beforeEach here will only slow your tests by making Mocha execute code that’s not required multiple times.

2. Setting up configurations required for a single test. Again, you should consider moving this configuration to the test that depends on it.

Mocha beforeEach Examples

1. Printing comment to console

Just like the code sample you saw earlier, a simple but helpful example for the usage of beforeEach could be printing a message to the console before each test run.

describe("Tests with beforeEach", function () {
  let testRan = 0;
  beforeEach(function () {
    testRan++;
    console.log("Initialising... Test " + testRan);
  });

  it("Test1", function () {
    //write test logic here
  });

  it("Test2", function () {
    //write test logic here
  });
});

Running the test in the above code will give you the following output:

  Tests with beforeEach
Initialising... Test 1
    ✔ Test1
Initialising... Test 2
    ✔ Test2

The logic is pretty basic. We’re simply increasing the value for testRun each time the beforeEach function runs.

2. Deleting Resources from Previous Tests

Let’s say your test generates some resources like files in the actual application. You can use the beforeEach method to clean such files before running the test in your suit. This can be good for keeping things clean and reducing the over-usage of resources like databases and file systems.

describe("This test an application that dumps data to a file", function () {

	//FileManager is a custom class from an application that creates and save data to a text file
	const fileManager = new FileManager();

	beforeEach(function () {
		fileManager.clearAll();
	})

	it("Test1", function () {
		//Your test goes here
	});

	it("Test2", function () {
		//Another test goes here
	});
});

In the above code, FileManager is a custom class from our testing application. Using Mocha’s beforeEach hook, we call the clearAll() method from the class to delete all old files and make sure each test starts with new files.

3. Configure Global Resources

Everyday use of beforeEach is configuring global resources to multiple tests in your suite. This reduces code duplication and increases consistency in tests.

describe("This test an application that dumps data to a file", function () {
  //FileManager is a custom class from an application that creates and save data to a text file
  const fileManager = new FileManager();
  let testRan = 0;
  beforeEach(function () {
    testRan++;
    fileManager.setSavePath("/assets/" + testRan);
  });

  it("Test1", function () {
    //Your test goes here
  });

  it("Test2", function () {
    //Another test goes here
  });
});

The above code still uses the FileManager class from the last example. However, this time it’s using the beforeEach method to configure where new files should be saved.

We reused the testRun counter here again, but this time we’re using the value to set the savePath for each file from a test. For example, the file from the first test will have “/assets/1” as the path. Meanwhile, the second test will have “/assets/2” as the path. This approach saves us the extra work of setting the savePath multiple times per test.

What Is the Use of beforeEach?

The beforeEach method has many uses, as seen from the above examples. But in summary, the following are some of the primary uses.

  • You can use beforeEach to execute specific code and functions before each code in your suite fires. Hence, this is a good option for making the data, including mocks that your tests depend on, available.
  • It reduces code duplication. Duplicating the same code in multiple places makes maintaining code more complex. For example, if the requirement for a duplicated code changes, you’ll be required to update all duplicates. Also, forgetting to update all duplicates may lead to inconsistent test behavior. Hence the use of beforeEach for common code means you only have to write it once, and then you can use it multiple times across multiple tests.

Summing Up

In this post, we explained what beforeEach is. In short, it’s a function that runs before each test in your suite.

We also looked at some examples of Mocha’s beforeEach with code samples. These examples range from simply printing a message to the console just before running each test to deleting resources generated by previous tests to reset the state of an application just before each test runs. In addition, we looked at when it’s a good idea to use Mocha’s beforeEach and when it’s not. Finally, you shouldn’t use beforeEach for code your test suite won’t use across multiple tests.

Expand Your Test Coverage

Fast and flexible authoring of AI-powered end-to-end tests — built for scale.
Start Testing Free