Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

295
Views
How to mock a simple global variable in Jest

I'm attempting to create unit tests for a function that is already written because I need to add some new code to it. This function uses a globally-scoped variable, desArray that is defined several hundred lines up, near the top of the file.

var desArray = [];

This variable is then populated later with an ajax call inside of the $(document).ready() function.

$(document).ready(function() {

    [...]

    $.ajax({
        [...]
        success: function (response) {
            response.data.forEach(item => {
                desArray.push(item);
            });
            [...]
        }
    });

    [...]

});

Obviously, since I'm trying to write unit tests, I just want to "replace" or, I presume, "mock" the desArray variable inside the test. Otherwise, it becomes an integration test because it's hitting API calls and such.

I have found loads of information on how to mock functions with Jest, but almost nothing about how to mock a simple variable with Jest. The only thing I have found is to try overriding it in the test:

global.desArray = [...];

This, sadly, does not work. The desArray variable remains an empty array in the function I'm testing.

Any ideas?

EDIT: For reference, here is the specific function that I want to test with my unit testing:

/**
 * Populates the Weight Type dropdown
 * and pre-selects an option from its list based on criteria.
 *
 * @param {jQuery} selectElement The jQuery-wrapped Select element
 * @param {string[]} deliveredWeight Weight field from tender broken into an array
 * @param {string} weightTypeQualifier Code to identify the type of weight
 */
const preSelectWeightType = (selectElement, deliveredWeight, weightTypeQualifier) => {
    for (let c = 0; c < desArray.length; c++) {
        const thisOption = $(new Option(desArray[c].description, desArray[c].id));
        selectElement.append(thisOption);
        if (desArray.length === 1) {
            thisOption.attr("selected", true);
        }
        if (desArray[c].description === deliveredWeight[1]) {
            thisOption.attr("selected", true);
        }
        if (weightTypeQualifier === desArray[c].qualifier) {
            thisOption.attr("selected", true);
        }
    }
};
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!