NodeJS中的疑难解答AWS模拟

时间:2019-06-20 13:10:09

标签: node.js jestjs aws-sdk sinon aws-sdk-mock

我进行了以下测试:

const AWSMock = require('aws-sdk-mock');
const AWS = require('aws-sdk');
const sinon = require('sinon');

function sendMetric() {
    const cloudwatch = AWS.CloudWatch();
    cloudwatch.putMetricData();
}

describe('Meh', () => {

    it('meh', () => {
        let sendMetricSpy = sinon.spy();
        AWSMock.mock('CloudWatch', 'putMetricData', sendMetricSpy);
        sendMetric();
        expect(sendMetricSpy.calledOnce).toEqual(true);
    });
});

我希望测试能够通过,因为我已经完成了the documentation所说的话。这是我试图在实际代码中实现的精炼示例。

运行测试的实际输出是:

 FAIL  functions/monitor/__test__/j.test.js
  Meh
    ✕ meh (10ms)

  ● Meh › meh

    expect(received).toEqual(expected) // deep equality

    Expected: true
    Received: false

      14 |         AWSMock.mock('CloudWatch', 'putMetricData', sendMetricSpy);
      15 |         sendMetric();
    > 16 |         expect(sendMetricSpy.calledOnce).toEqual(true);
         |                                          ^
      17 |     });
      18 | });
      19 | 

我不知道如何进一步解决此问题。

我也尝试过setting the aws-sdk object explicity,其结果相同。

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

回答了我自己的问题:putMetricData调用需要传递一个具有正确属性的对象。工作示例:

const REALAWS = require('aws-sdk');
const sinon = require('sinon');
const AWS = require('aws-sdk-mock');

const metricParams = {
    MetricData: [
        {
            MetricName: 'ServiceIsHealthy',
            Dimensions: [
                {
                    Name: 'Stage',
                    Value: 'foo',
                },
            ],
            StorageResolution: '60',
            Timestamp: new Date(),
            Unit: 'None',
            Value: '1',
        },
    ],
    Namespace: 'namespace',
};

test('Should return API Keys',  () => {

    const putMetricData = () => {
        const cloudwatch = new REALAWS.CloudWatch();
        return cloudwatch.putMetricData(metricParams)
            .promise();
    };

    const sinon = require('sinon');
    const putMetricDataSpy = sinon.spy();

    AWS.mock('CloudWatch', 'putMetricData', putMetricDataSpy);

    const apiNames = putMetricData();
    sinon.assert.calledOnce(putMetricDataSpy);

});

If you pass the method nothing, or an empty object, it fails.