amazon-web-services - 使用 Sinon 存根 KMS
问题描述
我正在尝试存根 KMS 方法,就像我已经存根其他所有方法一样。我用的是sinon。
sandbox.stub(AWS.KMS.prototype, 'decrypt')
.returns(Promise.resolve("some string"))
这会引发错误“无法存根不存在的属性解密”。
我看过其他推荐使用的帖子aws-sdk-mock
,但我想避免这种情况。我已经有很多与 AWS 相关的单元测试,我不希望有一套实现方式与其他的不同。
解决方案
您可以使用stub.returnsThis()
存根链方法调用,这样您就不需要嵌套存根对象。它给你一个扁平的mKMS
对象。
例如
main.ts
:
import AWS from 'aws-sdk';
export function main() {
const aws = new AWS.KMS();
return aws.decrypt().promise();
}
main.test.ts
:
import { main } from './main';
import sinon from 'sinon';
import AWS from 'aws-sdk';
import { expect } from 'chai';
describe('62400008', () => {
it('should pass', async () => {
const mKMS = {
decrypt: sinon.stub().returnsThis(),
promise: sinon.stub().resolves({
Plaintext: 'some string',
CiphertextBlob: Buffer.from('some string', 'utf-8'),
}),
};
sinon.stub(AWS, 'KMS').callsFake(() => mKMS);
const actual = await main();
expect(actual).to.be.deep.equal({
Plaintext: 'some string',
CiphertextBlob: Buffer.from('some string', 'utf-8'),
});
sinon.assert.calledOnce(mKMS.decrypt);
sinon.assert.calledOnce(mKMS.promise);
});
});
测试结果:
62400008
✓ should pass
1 passing (9ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
main.ts | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
推荐阅读
- php - 如何更改 PhpSpreadsheet 中的文本方向?
- javascript - 如何使用javascript为每一行添加前缀、后缀和中缀?
- python - 通过 mypy 使用 Python stdlib 的类型存根
- android - 华为自动阅读短信
- c++ - C++ 中的线程池不使用来自 args 的引用
- java - 如何安全地将查询参数合并到 Python 或 Java 中的 AWS TimeStream 查询中?
- python - 如何将列表写入新的 Excel 工作簿?
- c++ - C++:递归二分算法不断返回 0
- android - 蓝牙 Gatt 服务器 Android 设备 Null
- pandas - 使用多元素计算的交叉表