Introduction
Whenever we perform any testing, initialization before it starts and cleans up after it is executed, is necessary to be done globally. This global initialization and global cleanup are called global fixtures. The global fixture design allows us to define any number of global fixtures in any test file that constitutes a test module. The global fixture methods are monitored by an execution monitor, which makes error handling and reporting easier than initialization functions.
The global fixtures are applied to every test runner when we execute testing. The global fixtures are similar to life cycle hooks in react, but these are executed only once, unlike the hooks. We have two types of global fixtures.
- Global Setup Fixtures
- Global Teardown Fixtures
Let’s learn how the fixtures work with codes.
Global Setup Fixtures
Global setup fixtures run before you run your tests and start a server required to run your tests using a specified port. To create a global fixture, we must first export the mochaGlobalSetup from the script. We can import it by including the following lines into our code.
exports.mochaGlobalSetup = async function () {
this.server = await startServer({port: process.env.TEST_PORT});
console.log(`server running on port ${this.server.port}`);
};
Run the mocha --require fileName.cjs command to load this file so that we can create a setup globally. This code executes the global setup fixture and starts a server for your mocha tests before you mocha runs all the tests. The server can be started using the method startServer by providing a port number from the environment variables. Finally, a message “server running on port port-number” is printed to the console. The provided port number is displayed in the place of the port number in the message.
The created server will not shut down unless you stop it. So to stop it, we can use the Global teardown fixture.




