Incorporating an external JavaScript library in Jest for a React TypeScript project

I developed a React TypeScript application via create-react-app. I have a class called CustomConverter that depends on an external JS library, starting with the following code:

var ExternalModule = function(ExternalModule) {
...
}

I can successfully utilize this library by including it in the index.html file and initializing it with var instance = ExternalModule(). However, when I attempt to run Jest tests for the CustomConverter class, I encounter a ‘ExternalModule is not defined’ error. What steps should I take to properly integrate this JavaScript library into my testing environment?

To get the external JavaScript library working with Jest for your React TypeScript project, try these steps:

  1. Install the Library: If the library is available on npm, install it using npm install library-name.
  2. Mock the Library: Create a mock file in the __mocks__ directory. For example, ExternalModule.js:
    module.exports = jest.fn(() => { /* mock implementation */ });
  3. Configure Jest: In your jest.config.js, make sure to set up moduleNameMapper:
    moduleNameMapper: { '^ExternalModule$': '/__mocks__/ExternalModule.js' }

These steps should help Jest recognize and integrate the external library correctly in your tests.