Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jestjs

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?

like image 537
doberkofler Avatar asked Nov 07 '25 16:11

doberkofler


2 Answers

You can simply use require to load your script. However, keep in mind that the script must be saved locally.

require('relative/path/to/your/script')

Some more interesting information here : https://info343.github.io/jest.html

like image 155
Guillaume Meral Avatar answered Nov 12 '25 17:11

Guillaume Meral


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!

like image 26
Frank Avatar answered Nov 12 '25 15:11

Frank



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!