0

我正在尝试存根对 aws 参数存储 (PS) 的调用。但即使我以多种方式添加了存根,它总是会实际调用 aws PS。

我正在尝试测试的方法

function getParamsFromParamterStore() {
    return ssm.getParametersByPath(query).promise();
}

我尝试的一种存根方法

var ssm = new AWS.SSM();
stub1 = sinon.stub(ssm, 'getParametersByPath').returns({promise: () => {}});
moduleName.__get__('getParamsFromParamterStore')();

但这实际上调用了 PS。

注意:因为这是我rewire用来访问它的私有函数(未导出)。

4

1 回答 1

2

这是单元测试解决方案:

index.js

const AWS = require('aws-sdk');
const ssm = new AWS.SSM();

function getParamsFromParamterStore(query) {
  return ssm.getParametersByPath(query).promise();
}

index.test.js

const rewire = require('rewire');
const sinon = require('sinon');
const { expect } = require('chai');
const mod = rewire('./');

describe('60447015', () => {
  it('should pass', async () => {
    const ssmMock = { getParametersByPath: sinon.stub().returnsThis(), promise: sinon.stub().resolves('mock data') };
    const awsMock = {
      SSM: ssmMock,
    };
    mod.__set__('ssm', awsMock.SSM);
    const actual = await mod.__get__('getParamsFromParamterStore')('query');
    expect(actual).to.be.eq('mock data');
    sinon.assert.calledWithExactly(ssmMock.getParametersByPath, 'query');
    sinon.assert.calledOnce(ssmMock.promise);
  });
});

覆盖率 100% 的单元测试结果:

  60447015
    ✓ should pass


  1 passing (30ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.js |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
于 2020-02-28T08:33:40.423 回答