Mastering Jest Global Variables for Seamless Testing

Learn how to effectively use Jest global variables in your tests. Enhance your testing process with best practices and examples.

Get Started free
Home Guide Understanding Jest-Globals

Understanding Jest-Globals

By Mohit Joshi, Community Contributor -

Global Variables can be accessed and modified by any object or function across the code. They become extremely useful when you have to store values that have to be used across different parts of the project, such as configuration and values of global objects and functions. 

However advantageous it seems, there are some challenges, too, such as difficulty tracing out issues in your code, especially when different parts of the code interact with the same global state. Moreover, testing becomes more challenging due to the integration of several components, one component affecting the outcome of another. 

While testing JavaScript-based applications, Jest stands out as a powerful JavaScript testing framework. One of the primary reasons for implementing Jest is that it effectively manages global variables, mocks them during tests, and more.

What is the Jest framework?

Jest is an open-source JavaScript-based testing framework that supports projects on Angular, React, Vue, Babel, TypeScript, and more. The primary purpose of implementing Jest is to ease the process of testing complex web applications. It works out-of-the-box for many front-end frameworks by significantly reducing the configuration time and complexities. 

Jest extends its support to test any JavaScript-based codebase. Also, it doesn’t rely heavily on third-party applications, which makes it simpler and more handy. It is also a faster option when executing several test scripts. 

What is a Global Variable?

A global variable is accessible across all the project files without having to be imported or defined in each file. The key purpose of global variables is to keep the codebase simpler and cleaner by allowing commonly used essential variables to be used without importing them every time. 

Jest provides several global variables, such as describe, it, test, expect, and more. These variables are part of the Jest Global environment and are accessible in each test file without the need to import. 

Understanding Jest Globals

The Jest Global environment provides several global variables that can be used in every test file within a Jest project without needing to import or define them. The primary advantage of Jest Globals is that they simplify the process of writing test scripts by providing built-in methods, assertions, logic, and more, all readily available without defining them. 

1. Common Jest Globals

This section explains some global variables that come along with Jest and are frequently used in any Jest project. 

  • describe

It is used to group several tests under one block such that all the tests under the block are related to each other. It organizes test cases and helps in creating a test suite. For instance, if you have a ‘calculator’ object with class, ‘addition’. To test we created two tests, and we can put these two tests under one block. 

class Calculator {
  multiply(a, b) {
    return a * b;
  }

describe('Addition function', () => { 


test('add 2 + 3 to equal 5', () => { expect(calculator.add(2, 3)).toBe(5); }); 
test('multiplies 0+ 5 to equal 5', () => { expect(calculator.add(0, 5)).toBe(5); }); 



});
  • test/it 

These global variables are used for defining the test case. The ‘test’ and ‘it’ variables are used interchangeably and can be used for the same context.

test('add 2 + 3 to equal 5', () => { expect(calculator.add(2, 3)).toBe(5); }); 

2. Lifecycle Methods

Lifecycle Methods are those methods that are executed at a specific period in the test. In this section. This section describes the lifecycle methods available in the Jest. 

  • beforeAll and afterAll

The beforeEach and afterEach functions are executed once before and once after the tests, respectively. The beforeAll function can be used to set up the server, initialize the database, and more. The afterAll function can be used to close the server after tests, stop database connections, and more. 

beforeAll(() => {
  // Setup code here
});

afterAll(() => {
  // Teardown code here
});
  • beforeEach and afterEach

The beforeEach and afterEach functions execute a piece of code before and after each test case, respectively. The primary purpose of the function is to set up a consistent starting environment before or after each test case. 

Moreover, if it is used globally, it is executed before/after each test case. However, if it is executed within a describe function, then it is executed before/after each test of that block only. 

beforeEach(() => {
  // Setup code here
});

afterEach(() => {
  // Teardown code here
});

How to Mock Global Variables in Jest?

Mocking refers to the technique of isolating test components by temporarily replacing the behaviour of global variables. In simpler words, mocking helps isolate certain components during test execution to prevent the impact of global variables on the test results. 

Let’s discuss a few methods to mock global variables in Jest. 

1. Using the global object

To mock a global variable using this method, we need to set up the mock in ‘beforeEach’ and clean up the mock in ‘afterEach’

For example, you want to mock the ‘date’ object so that during the test, you receive the mocked date instead of the actual one. 

beforeEach(() => { const mockDate = new Date(2024, 0, 1); // January 1, 2024 

//creating a mock function
global.Date = jest.fn(() => mockDate); });

//cleaning up the mock
afterEach(() => { global.Date = Date; });

// testing if it returns the mocked data
test('should return the mocked date', () => { expect(getCurrentDate()).toBe('Mon Jan 01 2024'); });

2. Using setup Files

In this method, some code is executed before running each test file. It is useful when applying global mocks for each test suite at once. 

First, create a setup file, jest.setup.js.

// Mocking global Date 
const mockDate = new Date(2024, 0, 1); // January 1, 2024 
global.Date = jest.fn(() => mockDate);

Configure your Jest project to use the setup file by including the following script inside the package.json file under the jest section. 

{ 
"jest": {
 "setupFiles": ["./jest.setup.js"]
}
 }

3. Using spy with mockReturnValue

In this method, jest.spyOn creates a spy on a method or constructor, allowing you to track how it is called. The mockReturnValue configures the spy to return a specific value whenever the spied method or constructor is called.

beforeEach(() => {
    // Create a mock date
    const mockDate = new Date(2024, 0, 1); // January 1, 2024
   
    // Spy on the Date constructor and mock its return value
    jest.spyOn(global, 'Date').mockReturnValue(mockDate);
  });
 
  afterEach(() => {
    // Restore the original Date constructor
    global.Date.mockRestore();
  });

4. Using Object.defineProperty

It is a method available in Jest that defines a new property or modifies an existing property to mock Jest variables. 

beforeEach(() => {
    // Mock the Date constructor
    const mockDate = new Date(2024, 0, 1); // January 1, 2024
   
    // Use Object.defineProperty to redefine Date
    Object.defineProperty(global, 'Date', {
      value: jest.fn(() => mockDate),
      writable: true,
      configurable: true
    });
  });

In all the methods described above, you can verify that you received the mocked data by creating a test script, as shown below.

// testing if it returns the mocked data
test('should return the mocked date', () => { expect(getCurrentDate()).toBe('Mon Jan 01 2024'); });

How to Run a Jest Test?

Now, to practically understand how to run a Jest test, implement two tests—one for a Vanilla JavaScript project and the other for a React project. 

Prerequisites

  1. Ensure that Node.js is installed on your system, with version 14 or later.
  2. Next, install an IDE of your preference; for this example, we’ll be using Visual Studio Code.
  3. You must be familiar with the concepts of JavaScript and React.Js.

Installing & Configuring Jest

First, start by initializing a NodeJS project with the following command. 

npm init -y

Now, install Jest in your project with the following command. 

npm install jest

Jest is finally installed on your project. Now, you can start by creating two separate projects, React and Vanilla JavaScript projects respectively.

Vanilla JavaScript project 

Step 1: Create an application file to be tested. Let’s create a basic example. 

function sum(a, b) {
    return a + b;
  }
 
  module.exports = sum;

Step 2: Create a test file. 

const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

Step 3: Specify the test in your package.json file. 

{
  "name": "jest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "jest"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "jest": "^29.7.0"
  }
}

Step 4: Run the test with the help of the following command. 

npm test

Vanilla JS output

React Project 

Step 1: Install a React application

Create a new React app with the following command. Name this project jest-tutorial.

npx create-react-app basic-app

Next, start the app. 

npm start

Step 2: Configure the test renderer

To render the JavaScript objects without DOM, install react-test-renderer in your project with the following command.

npm install react-test-renderer

Step 3: Create a React application to perform testing

Create a React application for which you must write multiple tests using Jest. 

Write the following code inside the directory:

basic-app/src/components/HelloWorld.js.
import React from 'react'

function HelloWorld() {
  return (
    <div>
        <h1>
            Hello World
        </h1>
    </div>
  )
}

export default HelloWorld

Also, update the basic-app/src/App.js file with the following script.

import React, { Component } from 'react';
import HelloWorld from './components/HelloWorld';

class App extends Component {
  render() {
    return (
      <HelloWorld/>
    );
  }
}

export default App;

Step 4: Create a test file 

Update the existing App.test.js file with the following script. 

import React from 'react';
import { render, screen } from '@testing-library/react';
import HelloWorld from '../components/HelloWorld';

test('renders the "Hello World" message', () => {
  render(<HelloWorld />);
  const helloWorldText = screen.getByText('Hello World');
  expect(helloWorldText).toBeInTheDocument();
});

Step 5: Run the test

After you have written the test file, follow the command to run the test on the root directory of your project ./basic-app.

npm test

React JS output

Why choose Cloud Selenium Grid to Run Jest Tests? 

A Cloud Selenium Grid gives an edge over conventional testing as you can run multiple tests simultaneously and leverage a vast combination of devices and operating systems in one place without relying upon physical setups. 

Talk to an Expert

BrowserStack Automate is a cloud-testing platform that provides 3500+ real desktop and mobile browser combinations to effectively test your products. It offers several other features, such as Cloud Selenium Grid, cross-browser testing, responsive testing, Integrations with CI/CD tools, and more. 

BrowserStack Automate Banner

Jest is an immensely popular JavaScript-testing framework that offers a range of testing features, such as isolation testing, snapshot testing, and more. Global Variables are variables that can be accessed across the project without importing or defining them each time. Jest offers several global variables, such as describe, test, beforeEach, and afterEach. 

Mastering Jest global variables is key to writing efficient and organized tests. By leveraging these variables, you can streamline your test setup and improve code quality.

Integrate your Jest tests with BrowserStack Automate to further enhance your testing process. Run your tests on a cloud-based Selenium Grid with real devices and browsers and enjoy seamless CI/CD integration. BrowserStack Automate helps you accelerate test execution, improve coverage, and deliver flawless applications faster.

Try BrowserStack Now

Tags
Automation Frameworks Automation Testing Testing Tools

Featured Articles

Jest Framework Tutorial: How to use it?

How to Debug Jest Tests?

Optimize Jest Testing with BrowserStack Automate

Leverage the power of BrowserStack Automate to run your Jest tests across real browsers and devices.