单元测试AWS Lambda

时间:2019-12-17 19:35:25

标签: node.js unit-testing aws-lambda jestjs mocha

我是刚开始测试Node.js并发现很难为我的lambda函数提供单元测试用例的新手。我在网上阅读了一些建议,建议使用mocha / chai和lambda-tester模拟依赖关系。我还遇到了开玩笑的单元测试。对于选择哪种用例我感到困惑。

下面是我的lambda。有人可以帮我为下面的lambda编写基本的单元测试用例。 TIA。

const AWS = require('aws-sdk')
const zlib = require('zlib')
const https = require('https')

const ENV = process.env
;['hostname', 'port', 'username', 'encpass'].forEach(key => {
  if (!ENV[key]) throw new Error(`Missing environment variable: ${key}`)
})



let password



  function post(path, body, callback) {
    console.log('Request URL:', `https://${ENV.hostname}:${ENV.port}${path}`)
    const options = {
      hostname: ENV.hostname,
      port: ENV.port,
      path: path,
      method: 'POST',
      auth: `${ENV.username}:${password}`,
      headers: {
      'Content-Type': 'application/json',
      'Content-Length': Buffer.byteLength(body)
      }
    }
    https
      .request(options, response => {
        handleResponse(response, callback)
      })
      .on('error', err => {
        callback(err)
      })
      .end(body)
  }

function processEvent(event, context, callback) {
  const payload = Buffer.from(event.awslogs.data, 'base64')
   zlib.gunzip(payload, (err, res) => {
    if (err) return callback(err)
    const decodedPayload = JSON.parse(res.toString('utf8'))
    console.log('Decoded payload:', JSON.stringify(decodedPayload))
    const hasPipeline = ENV.pipeline 
    post('/_bulk' + hasPipeline, decodedPayload, callback)
  })
}


function decryptAndProcess(event, context, callback) {
  const kms = new AWS.KMS()
  const enc = { CiphertextBlob: Buffer.from(ENV.encpass, 'base64') }
  kms.decrypt(enc, (err, data) => {
    if (err) return callback(err)
    password = data.Plaintext.toString('ascii')
    processEvent(event, context, callback)
  })
}

exports.handler = (event, context, callback) => {
  if (password) {
    processEvent(event, context, callback)
  } else {
    decryptAndProcess(event, context, callback)
  }
}

编辑:我不确定如何模拟依赖关系,我也在寻找有关如何对node.js中特定功能进行单元测试的指南。我在问题中遗漏了什么

0 个答案:

没有答案
相关问题