I’m trying to set up jest testing for a huge legacy vanilla js files that is consantly calling global variables as well as JQuery. All those dependencies are not imported, they are added to the HTML via <script>
tags. Obviously, on a basic Jest set up, when I run the code that tests a specific file, all I see are error messages of "xxx is undefined"
.
I have tried the following but have come up short:
fileToTest.js
SomeGlobalVariable.hello();
AMillIoinOtherCallsToGlobalStuff.hey().whatsup();
$(document).ready(() => {
AnotherMillionCallsToGlobalStuff();
});
function theOneIWantToTest(){
const a = Big("0"); // When running the test file, jest can't see Big.js library
return false;
}
module.exports = {
theOneIWantToTest
};
fileToTest.test.js
const viewOrder = require('../js/fileToTest');
describe("fileToTest.js", () => {
describe("theOneIWantToTest", () => {
it("return true", () => {
expect(theOneIWantToTest()).toBeFalsy();
})
});
});
What have I tried to achieve this? Well:
jestSetUpFiles.js
Defined all global variables here and mocked functions.
jest.config.js
Trie to add here all the scripts that are appended via
const config = {
setupFiles: [
"./node_modules/big.js/big.js",
"./frontend/js/jquery-1.9.1",
"./frontend/js/jquery-ui.js",
"./frontend/js/jquery.dialogify.js",
"./frontend/js/tappy.js",
"./jestSetUpFiles"
],
testEnvironment: "jsdom"
};
module.exports = config;
I tried to add Big.js which is a library that theOneIWantToTest
uses directly in the code, but it didn’t work. When I try to run the test, it complains it can’t find Big
. So I tried loading it direclty on jestSetUpFiles, such that:
/*
* Loading non mocked libraries because jestSetUpFiles did not work
* */
Big = require("./node_modules/big.js/big.js");
But obviously that doesn’t work, because then the code would have to access it such that Big.Big()
.
Not sure what else to try. Any ideas?