单元测试 AWS Lambda CDK

时间:2021-02-23 17:18:56

标签: typescript unit-testing aws-lambda jestjs aws-cdk

我在对依赖于引用的 lambda 层内的包的 lambda 函数模块进行单元测试时遇到问题。

我的模块看起来像这样

/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);
};

为了测试这个功能,我想模拟正在导入的模块。 我的尝试...

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({});
  });
});

当然,Jest 无法模拟它找不到的模块。

我的 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"]
}

我什至通过这是我的 package.json

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

任何想法将不胜感激。

谢谢!

0 个答案:

没有答案