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

Moh*_*shi 4 unit-testing node.js jestjs aws-lambda

const invokeApi = require("/opt/nodejs/kiwiCall");\nconst decrypt = require("/opt/nodejs/encryption");\nconst cors = require("/opt/nodejs/cors");\n
Run Code Online (Sandbox Code Playgroud)\n\n

当我通过手动模拟模拟目录中的这些依赖项来测试我的index.js文件时,如下所示:

\n\n
__mocks__ \n    |_invokeApi\n    |_decrypt\n    |_cors\n
Run Code Online (Sandbox Code Playgroud)\n\n

它说

\n\n
FAIL  ./index.test.js\n  \xe2\x97\x8f Test suite failed to run\n\n    Cannot find module \'/opt/nodejs/kiwiCall\' from \'index.js\'\n\n    However, Jest was able to find:\n        \'../../../../lambdas/Flights/Locations/index.js\'\n\n    You might want to include a file extension in your import, or update your \'moduleFileExtensions\', which is currently [\'js\', \'json\', \'jsx\', \'ts\', \'tsx\', \'node\'].\n\n    See https://jestjs.io/docs/en/configuration#modulefileextensions-array-string\n\n      1 | "use strict";\n      2 | \n    > 3 | const invokeApi = require("/opt/nodejs/kiwiCall");\n
Run Code Online (Sandbox Code Playgroud)\n\n

想知道如何在 inedx.test.js 文件中模拟 AWS lambda 的依赖关系

\n

Phi*_*hil 5

在 package.json 或 jest.config 中,您可以为该目录添加 moduleNameMapper。

  "jest": {
    "moduleNameMapper": {
      "/opt/nodejs/(.*)": "<rootDir>/../nodejs/$1"
    },
  },
Run Code Online (Sandbox Code Playgroud)