How to Globally Mock an External Library in Jest
Say you’re using an external library that’s loaded directly in your single page app with a script tag.
<script src="//host.com/someExternalLibrary.min.js"></script>And say that library (in this instance an error logger) is available in the global namespace as externalLibrary and you hit it repeatedly and directly in your app code via something like:
// myModule.jsmyAsyncFunc()
.then(resp => {
if(resp.condition) {
doStuff()
} else {
throw new Error('DISASTER!')
}
})
.catch(e => {
externalLibrary.logError(e)
})
Now say you’re testing that your function throws on !resp.condition in Jest. How do you avoid the externalLibrary is not defined error since you’re not importing it directly via a module? And say you found the Jest documentation about mocking globals incredibly confusing? And to the extent that you do understand the documentation you sure as hell don’t want to manually import a mock into every single test file?
Answer: Setup Files in Jest Configuration
setupFiles “runs some code to configure or set up the testing environment before each test.” Mocking this external library here will make it available universally across your Jest environment. You can also save yourself some time by importing boilerplate for things like React components.*
// package.json"jest": {
"setupFiles": [
"<rootDir>/jest/globals.js"
]
}// jest/global.js
import React from "react";global.React = React;
global.externalLibrary = {
logError: err => {
console.log(err); // will output errors during Jest run
}
};
Voila.
* Please leave me a comment if this is an anti-pattern for some reason



