How to Globally Mock an External Library in Jest

<script src="//host.com/someExternalLibrary.min.js"></script>
// myModule.jsmyAsyncFunc()
.then(resp => {
if(resp.condition) {
doStuff()
} else {
throw new Error('DISASTER!')
}
})
.catch(e => {
externalLibrary.logError(e)
})
// 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
}
};

Staff Software Engineer. Making computers do stuff since 2011.

Love podcasts or audiobooks? Learn on the go with our new app.

Justin Tulk

Justin Tulk

Staff Software Engineer. Making computers do stuff since 2011.

More from Medium

Build an accessible “Skip to Content” anchor link with React.

Skiplink button user interface with content “Skip Navigation Links”.

Component Library Setup with React

An Introduction to performance.now()

a clock in a pink and green background

Considerations for writing React Components — Part 02: Function vs. Class components