The default test environment for Jest
is a browser-like environment using jsdom
which provides a window
object.
If the test environment is jsdom
then the window
object is accessible as either window
or global
.
Setting variables on window
then becomes as easy as doing the following:
window.VarA = 'foo'; // global.VarA works as well
window.VarB = 'bar'; // global.VarB works as well
The trickier part is getting those variables set before your code runs.
Consider the following config.js
module:
let param = "";
let url = "";
if (window.VarA !== undefined) {
param = window.VarA;
}
if (window.VarB !== undefined) {
url = window.VarB;
}
export const config = {
param,
url
}
If you use require
then the code doesn't run until the module is required, allowing for a test like this:
test('setting window variables', () => {
window.VarA = 'foo'; // global.VarA works as well
window.VarB = 'bar'; // global.VarB works as well
const { config } = require('./config'); // now require the module
expect(config.param).toBe('foo'); // SUCCESS
expect(config.url).toBe('bar'); // SUCCESS
});
On the other hand, if you use import
then the variables need to be defined on window
before the test runs since imports are hoisted and happen before any test code runs:
import { config } from './config'; // this runs first
test('setting window variables', () => {
window.VarA = 'foo'; // <= this doesn't affect config
window.VarB = 'bar'; // <= this doesn't affect config
expect(config.param).toBe('foo'); // FAIL
expect(config.url).toBe('bar'); // FAIL
});
So if you are using import
then you would need to use something like setupFilesAfterEnv
to set the window
variables before your test begins running:
// Configure Jest using setupFilesAfterEnv
// to run a module that sets the window variables
// so they are already set before the test begins...
import { config } from './config';
test('setting window variables', () => {
expect(config.param).toBe('foo'); // SUCCESS
expect(config.url).toBe('bar'); // SUCCESS
});