Mocking a lambda layer library for unit testing fails in jest

29 Views Asked by At

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:

enter image description here

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?

1

There are 1 best solutions below

0
Oussema Miled On

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

jest.mock('opt/nodejs/logger', () => ({
  logger: {
    debug: jest.fn((msg: string) => console.log('debug message: ', msg)),
    info: jest.fn((msg: string) => console.log('info message: ', msg)),
    error: jest.fn((msg: string) => console.log('error message: ', msg)),
    warn: jest.fn((msg: string) => console.log('warning message: ', msg)),
  },
}));