Global Fixtures
At first glance, global fixtures seem similar to root hook plugins. However, unlike root hooks, global fixtures:
- Are guaranteed to execute once and only once
- Work identically parallel mode, watch mode, and serial mode
- Do not share a context with tests, suites, or other hooks
There are two types of global fixtures: global setup fixtures and global teardown fixtures.
Global Setup Fixtures
To create a global setup fixture, export mochaGlobalSetup
from a script, e.g.,:
…or an ES module:
To use it, load this file when running Mocha via mocha --require fixtures.cjs
(or whatever you have named the file).
Now, before Mocha loads and runs your tests, it will execute the above global setup fixture, starting a server for testing. This won’t shut down the server when Mocha is done, however! To do that, use a global teardown fixture.
Global Teardown Fixtures
Just like a global setup fixture, a global teardown fixture can be created by exporting from a “required” script (we can put both types of fixtures in a single file):
…or an ES module:
You’ll note that we used this
in the fixture examples.
Global setup fixtures and global teardown fixtures share a context, which means we can add properties to the context object (this
) in the setup fixture, and reference them later in the teardown fixture.
This is more useful when the fixtures are in separate files, since you can just use JS’ variable scoping rules instead (example below).
As explained above—and below—test files do not have access to this context object.
When To Use Global Fixtures
Global fixtures are good for spinning up a server, opening a socket, or otherwise creating a resource that your tests will repeatedly access via I/O.
When Not To Use Global Fixtures
If you need to access an in-memory value (such as a file handle or database connection), don’t use global fixtures to do this, because your tests will not have access to the value.
Instead, use the global fixture to start the database, and use root hook plugins or plain old hooks to create a connection.
Here’s an example of using global fixtures and “before all” hooks to get the job done.
Note that we do not reference the server
object anywhere in our tests!
First, use a global fixture to start and stop a test server:
Then, connect to the server in your tests:
Finally, use this command to bring it together: mocha --require fixtures.mjs test.spec.mjs
.