哪个是在NodeJS中模拟调用aws ssm的最佳方法?

问题描述 投票:0回答:1

我正在尝试模拟对AWS的调用服务ssm:

const ssm = require("../awsclients/aws-client");

const getSecret = async secretName => {
  // eslint-disable-next-line no-console
  console.log(`Getting secret for ${secretName}`);
  const params = {
    Name: secretName,
    WithDecryption: true
  };

  const result = await ssm.getParameter(params).promise();
  return result.Parameter.Value;
};

module.exports = { getSecret };

[任何建议,我都是使用AWS-Lambdas的nodeJS的新手。 ?

node.js amazon-web-services aws-lambda mocha
1个回答
0
投票

您可以使用sinon.js之类的存根/模拟库。

例如

index.js

const ssm = require('./aws-client');

const getSecret = async (secretName) => {
  // eslint-disable-next-line no-console
  console.log(`Getting secret for ${secretName}`);
  const params = {
    Name: secretName,
    WithDecryption: true,
  };

  const result = await ssm.getParameter(params).promise();
  return result.Parameter.Value;
};

module.exports = { getSecret };

aws-client.js

module.exports = {
  getParameter() {
    return this;
  },
  async promise() {
    return 'real value';
  },
};

index.test.js

const { getSecret } = require('./');
const ssm = require('./aws-client');
const sinon = require('sinon');
const { expect } = require('chai');

describe('60695567', () => {
  it('should get secret', async () => {
    const promiseStub = sinon.stub().resolves({ Parameter: { Value: '123' } });
    sinon.stub(ssm, 'getParameter').callsFake(() => ({
      promise: promiseStub,
    }));
    const actual = await getSecret('token');
    expect(actual).to.be.eq('123');
    sinon.assert.calledWithExactly(ssm.getParameter, { Name: 'token', WithDecryption: true });
    sinon.assert.calledOnce(promiseStub);
  });
});

带有覆盖率报告的单元测试结果:

  60695567
Getting secret for token
    ✓ should get secret


  1 passing (25ms)

---------------|---------|----------|---------|---------|-------------------
File           | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
---------------|---------|----------|---------|---------|-------------------
All files      |      80 |      100 |   33.33 |      80 |                   
 aws-client.js |   33.33 |      100 |       0 |   33.33 | 3,6               
 index.js      |     100 |      100 |     100 |     100 |                   
---------------|---------|----------|---------|---------|-------------------
© www.soinside.com 2019 - 2024. All rights reserved.