How can I load a global script (<script src="">) in Jest

Viewed 528

I need to make a JavaScript script available as a global script tag for a unit test in Jest. I understand that Jest uses jsdom and in jsdom there is an api that allows to initialize the DOM and load script but I cannot seem to find a way on how to do this in Jest?

1 Answers

If you do not need to test the script itself, which, given the fact it is an external library, you shouldn't, you can mock it globally.

First of all you need to setup a jest setupFile, this file will be executed before test execution and the mocks available there should remain available for each test file, to do so write something like this in package.json or, better, in jest.config.js

"jest": {
  "setupFiles": [
    "<rootDir>/jest/globals.js"
  ]
}

Then create that file and write your global mocks there.

Now you will say "'Duh'? How do I mock the external library imported through the tag script?" Well, what I found useful for this and a number of other reason is to wrap the imported library in a separate module, this way you can use the wrapper throughout your code instead of using directly the globally imported external library, which will give you the possibility to mock the said module globally and voilĂ , it is done!

Related