首页 > 解决方案 > 使用 Sinon 存根 KMS

问题描述

我正在尝试存根 KMS 方法,就像我已经存根其他所有方法一样。我用的是sinon。

sandbox.stub(AWS.KMS.prototype, 'decrypt')
    .returns(Promise.resolve("some string"))

这会引发错误“无法存根不存在的属性解密”。

我看过其他推荐使用的帖子aws-sdk-mock,但我想避免这种情况。我已经有很多与 AWS 相关的单元测试,我不希望有一套实现方式与其他的不同。

标签: amazon-web-servicesunit-testingsinonaws-kms

解决方案


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

推荐阅读