Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest with typescript + lambda functions + lambda layers (AWS)

I have an issue with importing modules for my jest tests in a setup containing lambdas, lambda layers and tests. The file structure is as following:

backend/
├─ jest.config.js
├─ package.json
├─ babel.config.js
├─ layers/
│  ├─ tsconfig.json
│  ├─ aws_handler/
├─ lambdas/
│  ├─ tsconfig.json
│  ├─ some_lambda/
│  │  ├─ index.ts
├─ tests/
│  ├─ tsconfig.json
│  ├─ some_lambda.test.ts

When I run npm test I get the following error: Cannot find module '@libs/aws' or its corresponding type declarations.

So, when I don't test it works. In lambdas/some_lambda/index.ts I import a layer the following way:

import { lambda } from '@libs/aws';

and in the lambdas/tsconfig.json I specify the relative path to the layer

"baseUrl": "",
    "paths": {
      "@libs/aws": [
        "../lambda_layers/aws_handler"
      ],
    }

So, when running the lambda it can find the @libs/aws module but not when testing. Ok, so far so "good".

Somewhere in jest.config.js and/or package.json I need to specify where to find this module, but I struggle doing so. Can the jest.config.js somehow inherit or look at the lambdas/tsconfig.json file?

For example I read somewhere that adding this to package.json would help

"jest": {
    ...
    "rootDir": "./",
    "modulePaths": [
      "<rootDir>"
    ],
    ...
  }
}

or in jest.config.js I should specify moduleDirectories etc. Does anyone have a similar setup that can tell me how to approach this?

like image 659
Christian Hjelmslund Avatar asked Oct 24 '25 09:10

Christian Hjelmslund


1 Answers

You have to config moduleNameMapper for jest the same as what you did at tsconfig.js paths.

If you use ts-jest as a transformer, use their helper.

jest.config.js

const { pathsToModuleNameMapper } = require('ts-jest');
const { compilerOptions } = require('./lambdas/tsconfig');


module.exports = {
  // [...]
  modulePaths: [compilerOptions.baseUrl],
  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths),
}
...

Or you can do it without a helper:

  moduleNameMapper: {
    '^@libs/aws/(.*)$': '<rootDir>/lambda_layers/aws_handler/$1'
  },
like image 72
hoangdv Avatar answered Oct 25 '25 23:10

hoangdv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!