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);
}
}
};