您可以使用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 |
----------|---------|----------|---------|---------|-------------------