Unit testing AWS Lambda CDK

Viewed 825

I'm having issues unit testing a lambda function module that is dependent on a package inside the referenced lambda layer.

My module looks like so

/lambda/function/orderIdGenerator.ts

import { Order } from './structs';
import { generateHashedId } from '/opt/nodejs/node_modules/package_name/common';

export const orderIdGenerator = (order: Order): string => {
  const orderValues = Object.values(order);
  return generateHashedId(orderValues);
};

To then test this function I want to mock the module being imported. My attempt...

jest.mock('package_name/common');
import { Order } from 'lambda/function/structs';
import { orderIdGenerator } from '../../../lambda/function/orderIdGenerator';
import { generateHashedId } from '/opt/nodejs/node_modules/package_name/common';

describe('orderIdGenerator', () => {
  it('should call generateHashedId', () => {
    // GIVEN
    const fn = orderIdGenerator;
    // WHEN
    fn(({ foo: 'bar' } as unknown) as Order);
    // THEN
    expect(generateHashedId).toHaveBeenCalled();
  });

  it('should call generateHashedId with Order', () => {
    // GIVEN
    const fn = orderIdGenerator;
    // WHEN
    fn({} as Order);
    // THEN
    expect(generateHashedId).toHaveBeenCalledWith({});
  });
});

But of course Jest is not able to mock a module it cannot find.

My tsconfig.json

{
  "compilerOptions": {
    "target": "ES2018",
    "module": "commonjs",
    "lib": ["es2018"],
    "declaration": true,
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": false,
    "inlineSourceMap": true,
    "inlineSources": true,
    "experimentalDecorators": true,
    "strictPropertyInitialization": false,
    "typeRoots": [
      "./node_modules/@types",
      "./layer/nodejs/node_modules/@types"
    ],
    "baseUrl": ".",
    "paths": {
      "/opt/nodejs/*": ["layer/nodejs/*"]
    }
  },
  "exclude": ["cdk.out"]
}

I even through this is my package.json

  "jest": {
    "modulePaths": [
      "<rootDir>/node_modules/",
      "<rootDir>/layers/nodejs/node_modules/"
    ]
  }

Any ideas would be appreciated.

Thanks !

0 Answers
Related