Globals

Loading "Intro to Globals"
At its core, mocking is a dependency-management technique. Whether you depend on things like date and time, particular built-in APIs or globals, other modules or calls to third-party services—knowing which dependencies to allow in a test affects the type and scope of that test.
All dependencies you encounter can be divided into two groups:
  • Explicit dependencies (things you import() yourself);
  • Implicit dependencies (i.e. globals).
In this exercise, you learn how to mock global dependencies. Those are implicit since you don't import them manually and instead get them from the globalThis object of your environment, most commonly just referencing them by their name.
console.log(process.env.NODE_ENV)
^^^^^^^     ^^^^^^^
Above is a quick example of the global console object printing a message that contains an environment variable taken from another global process object and its env property.
Globals are also not limited to built-in native APIs, as you can create your own variables and expose them globally in your application!

Dangers of mocking globals

Mocking globals, however, can be quite dangerous. That is mostly due to the fact that globals are often the things you do not own. You don't own the console or the process object. You haven't defined them, have no access to their implementation, and aren't aware of countless intricacies they may have under the hood.
When mocking globals for testing purposes, your main concern becomes the integerity of your environment. In other words, you don't want to end up in a test environment where the process object behaves dramatically different than it does in production.
In this exercies block, you will learn how to mock global methods, values, and environment variables in a way that is safe and reliable. Without further ado, let's dive in!