我正在尝试存根KMS方法,就像我已经存根了其他所有东西一样。我用的是sinon。
sandbox.stub(AWS.KMS.prototype, 'decrypt')
.returns(Promise.resolve("some string"))这会抛出错误“无法存根不存在的属性解密”。
我看过其他推荐使用aws-sdk-mock的帖子,但我想避免这种情况。我已经有了很多与AWS相关的单元测试,我不希望有一个集的实现与其他集不同。
发布于 2020-06-16 23:44:11
我想出了一个解决方案..。
首先,我使用的是AWS方法的promise类型:
KMS.decrypt(params).promise()
因此,为了消除这个问题,我执行以下操作:
sandbox = sinon.createSandbox()
const mKMS = {
decrypt: sandbox.stub().returns({
promise: () => {Promise.resolve({
Plaintext: "some string",
CiphertextBlob: Buffer.from("some string", 'utf-8')
})}
})
}
sandbox.stub(AWS, 'KMS').callsFake(() => mKMS)另外,我承认我仍然在研究从那个Promise.resolve()返回什么样的对象--但是它已经成功地截断了该方法。
发布于 2021-03-25 13:16:56
您可以使用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 |
----------|---------|----------|---------|---------|-------------------https://stackoverflow.com/questions/62400008
复制相似问题