Globals
Loading "Intro to Globals"
Run locally for transcripts
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 will learn how to mock global dependencies. These 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 globalconsole
object printing a message that contains an environment variable taken from another globalprocess
object and itsenv
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, the integrity of your environment is your main concern. In other words, you donโt want a test environment where the process object behaves dramatically differently than it does in production.
In this exercise 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!