How to Inject Global in Jest
Why need to inject globals
My work requires to use a very old JavaScript style, in which everything is global. You have to give it some credit as it really convinent when using globals. It’s like a mom/dad you can ask for anything you want. On second thought, it’s probably better than mom/dad because most mom/dad will NOT always give you everything you want.
Anyone who works with globals in JavaScript knows the harm is greater than the benefit. So that’s why we try to use modules in JavaScript now.
But as work requirement, I have to work with it and also need to find a way to test it.
Why choose Jest
I’ve been using Jest
for a while and the 1st time I knew Jest was when I start learning React
, like most of the Jest
users. But over the times, Jest
is graduly taken over my heart, and lots of others hearts, I beleive.
How to inject globals in tests
As a new testing tool in JavaScript, Jest
is originated to support modules, but it does support the pre-module era.
There are 2 ways to inject glboals in Jest
, as far as I know:
- as part of the configuration
- as a setup file or setup files
The main difference between these 2 methods is the complexity. If your globals is a simple object/value, you can use it directly as part of the configuration. But if it’s more complex, e.g. it has functions, you need to use a setup file or multiple setup files for it.
Simple Object as Globals1
When providing a simple object/value as globals in Jest tests, you can put something like the following in your configuration file:
{
"globals": {
"ENV": "DEV",
"BASE_URL":"https://testapi.com/"
}
}
Then in your tests, your can directly using these variables.
Setup File2
If you need to use functions in globals, the above method will not work. You need to use setup file(s) to make it work.
First you need to specify the file(s) in your configuration:
{
"setupFiles":['./setup-jest.js']
}
Then in your js
files, you can use anything you want to as globals.
export const SOME_GLOBALS = {
env: 'DEV',
getUserID: () => 'Sam'
}
That’s all for now. Happy Testing!