在NodeJS中Mock调用aws-ssm的最佳方式是什么



我正在尝试模拟调用服务ssm到aws:

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新手?

您可以使用类似sinon.js.的stub/mock库

例如

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 |                   
---------------|---------|----------|---------|---------|-------------------

最新更新