I am trying to unit test my lambda using jest. In the lambda code, we have a line of code that relies on a package situated in the lambda layer.
import { logger } from 'opt/nodejs/logger';
...
logger.debug('a message');
The error is:
TypeError: Cannot read properties of undefined (reading 'debug')
Based on the jest documentation, the attribute moduleNameMapper is the way to go to be able to mock a library but it didn't work for me.
I have this folder structure:
The lambda layer contains the lib folder.
This is the content of jest.config.js
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
modulePaths: ['node_modules', '.'],
moduleNameMapper: {
'^opt/nodejs/logger$': '<rootDir>/../lib/src/logger.ts',
},
}
I also tried to put an absolute path (something like /User/.../lib/src/logger.ts) and '^opt/nodejs/(.*)$': '<rootDir>/../lib/src//$1' but still didn't work.
I feel like this is a kind of a problem where you're missing a very small detail, any idea how to fix this? alternatively, is there another way to do the mocking easily?

After I got enough of trying with the config in
jest.config.js, I switched to try withjest.mock()and iI got it working using: