【问题标题】:Stub KMS with Sinon使用 Sinon 存根 KMS
【发布时间】:2020-06-16 02:24:33
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: amazon-web-services unit-testing sinon aws-kms


    【解决方案1】:

    我想出了一个解决办法……

    首先,我使用的是 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() 返回的确切对象类型——但它成功地存根方法。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2016-08-09
        • 2014-11-29
        • 2020-12-12
        • 2015-11-28
        • 2021-07-26
        • 2019-12-04
        • 1970-01-01
        • 2015-04-18
        • 1970-01-01
        相关资源
        最近更新 更多