This post goes over how to mock Amplitude Browser SDK with Jest.
Problem
I installed Amplitude Analytics SDK in my frontend project:
npm install @amplitude/analytics-browser
But when I ran my Jest tests, I got the error:
TypeError: (0 , analytics_core_1.UUID) is not a function
at ./node_modules/@amplitude/analytics-browser/src/config.ts:283:9
Solution
I created a mock file amplitude-analytics-browser-mock.js:
mkdir -p __mocks__ && touch __mocks__/amplitude-analytics-browser-mock.js
With the code:
// __mocks__/amplitude-analytics-browser-mock.js
module.exports = {
init: jest.fn(),
track: jest.fn(),
identify: jest.fn(),
Identify: jest.fn(),
};
I updated my Jest config’s moduleNameMapper:
/** @type {import('jest').Config} */
const config = {
moduleNameMapper: {
'^@amplitude/analytics-browser$':
'<rootDir>/__mocks__/amplitude-analytics-browser-mock.js',
},
};
module.exports = config;
Then my tests passed!