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?
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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With