简体   繁体   English

使用 jest 对 aws lambda 进行单元测试

[英]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目录中手动模拟这些依赖项来测试我的 index.js 文件时,如下所示:

__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想知道如何在 inedx.test.js 文件中模拟 AWS lambda 的依赖项

In your package.json or jest.config you could add a moduleNameMapper for that directory.在您的 package.json 或 jest.config 中,您可以为该目录添加一个 moduleNameMapper。

  "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.这在我部署到 AWS Lambda 时有效,因为/opt/shared存在并且可以正确引用。 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.如果我使用sam local invoke Function1在我的机器上运行它,它也可以工作,因为它在容器中运行,这使得/opt/shared可用于代码。

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如果我只是这样做: jest.mock('/opt/shared') ,我得到: 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.我正在使用 moduleNameMapper 将绝对路径映射到我的存储库中另一个位置到我存储层的位置。

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.在您的情况下,您可以使用正则表达式来匹配/opt/nodejs/并将其映射到其他地方。 Hope that helped.希望有所帮助。

EDIT:编辑:

I completely changed my approach and used babel-plugin-module-resolver with babel-rewire.我完全改变了我的方法,并使用 babel-plugin-module-resolver 和 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 .设置非常简单,您只需要在.babelrc设置一个 babel 别名。

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.将此与 IDE jsconfig.json路径别名结合使用,您将获得完整的 IDE 支持。

{
  "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);然后你可以使用jest.doMock('/opt/config/config', mockConfig);引用你的层jest.doMock('/opt/config/config', mockConfig);

EDIT 2: Found a way to get Jest to mock it.编辑 2:找到了让 Jest 嘲笑它的方法。 Just slip {virtual: true} into the mock!只需将{virtual: true}滑入模拟中!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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