简体   繁体   中英

Unit test for aws lambda using jest

const invokeApi = require("/opt/nodejs/kiwiCall");
const decrypt = require("/opt/nodejs/encryption");
const cors = require("/opt/nodejs/cors");

When I am testing my index.js file by manual mocking these dependencies in mocks directory as follows:

__mocks__ 
    |_invokeApi
    |_decrypt
    |_cors

it says

FAIL  ./index.test.js
  ● Test suite failed to run

    Cannot find module '/opt/nodejs/kiwiCall' from 'index.js'

    However, Jest was able to find:
        '../../../../lambdas/Flights/Locations/index.js'

    You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['js', 'json', 'jsx', 'ts', 'tsx', 'node'].

    See https://jestjs.io/docs/en/configuration#modulefileextensions-array-string

      1 | "use strict";
      2 | 
    > 3 | const invokeApi = require("/opt/nodejs/kiwiCall");

Wanted to know how can I mock the dependencies of AWS lambda in inedx.test.js file

In your package.json or jest.config you could add a moduleNameMapper for that directory.

  "jest": {
    "moduleNameMapper": {
      "/opt/nodejs/(.*)": "<rootDir>/../nodejs/$1"
    },
  },

I have pretty much the same issue. I have defined a layer which contains common code that's shared between other functions in my project. My project structure looks something like this:

project/
  functions/
    function1/
      app.js
    function2/
      app.js
  shared/
    shared.js

I import my shared library like this:

const { doSomething } = require('/opt/shared');

exports.handler = async (event) => {
  const result = await doSomething();
  // etc...
  return {statusCode: 200};
}

This works when I deploy to AWS Lambda because the /opt/shared exists and it can be referenced correctly. It also works if I run this on my machine using sam local invoke Function1 because it's running in a container, which makes /opt/shared available to the code.

However, I'm struggling to work out how I can mock this dependency in a unit test. If I simply do this: jest.mock('/opt/shared') , I'm getting: Cannot find module '/opt/shared' from app.test.js

So I managed to figure out something based on my repository.

I'm using the moduleNameMapper to map the absolute path to another location in my repository to where I have the layer stored.

Eg.

moduleNameMapper: {'^/opt/config/config': '<rootDir>/src/layers/layers-core/config/config'}

In your case you could use a regex expression to match /opt/nodejs/ and map it elsewhere. Hope that helped.

EDIT:

I completely changed my approach and used babel-plugin-module-resolver with babel-rewire. I did this because the above method was incompatible with rewire. It's quite easy setup and you just need to setup a babel alias within .babelrc .

eg.

{
  "plugins": [
    ["rewire"],
    ["babel-plugin-module-resolver", {
      "alias": {
        "/opt/config/config": "./src/layers/layers-core/config/config",
        "/opt/utils/util-logger": "./src/layers/layers-core/utils/util-logger",
        "/opt/slack": "./src/layers/layers-slack/slack"
      }
    }]
  ]
}

Combine this with IDE jsconfig.json path alias and you get full IDE support.

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2018",
    "baseUrl": "./",
    "paths": {
      "/opt/config/config": ["src/layers/layers-core/config/config"],
      "/opt/utils/util-logger": ["src/layers/layers-core/utils/util-logger"],
      "/opt/slack/*": ["src/layers/layers-slack/slack/*"],
    }
  },
  "exclude": ["node_modules", "dist"]
}

You can then reference your layers with jest.doMock('/opt/config/config', mockConfig);

EDIT 2: Found a way to get Jest to mock it. Just slip {virtual: true} into the mock!

jest.doMock('/opt/config/config', mockConfig, {virtual: true});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM