简体   繁体   中英

Can't mock AWS CloudWatchLogs filterLogEvents function using sinon

I have a function that works fine.

const { CloudWatchLogs } = require('aws-sdk');
class MyClass {
    async _getLogs(config, filter) {
        const cwl = new CloudWatchLogs();
        return await cwl.filterLogEvents({
            logGroupName: config["group-name"],
            filterPattern: filter,
            logStreamNames: [config["stream-name"]]
        }).promise();
    }
}

I try to mock it as I usually would but it fails citing TypeError: Cannot replace non-existent own property filterLogEvents .

const { MyClass } = require('../../lib/myClass ');
const { CloudWatchLogs } = require('aws-sdk');
const sinon = require('sinon');
describe('_getLogs()', function() {
    it('...', async function() {
        const mock = sinon.fake.resolves('x');
        const obj = { 
            "group-name": "a",
            "stream-name": "b"
        };
        sinon.replace(CloudWatchLogs.prototype, 'filterLogEvents', mock);
        const mc = new MyClass();
        await mc._getLogs(obj , "x");
    });
});

What's going on? Clearly the filterLogEvents property is there as my code works as expected. I also have no problem mocking other functions in this file.

You could use Link Seams with CommonJS . Therefore, you need to use proxyquire package.

Eg

index.js :

const { CloudWatchLogs } = require('aws-sdk');

class MyClass {
  async _getLogs(config, filter) {
    const cwl = new CloudWatchLogs();
    return await cwl
      .filterLogEvents({
        logGroupName: config['group-name'],
        filterPattern: filter,
        logStreamNames: [config['stream-name']],
      })
      .promise();
  }
}

module.exports = { MyClass };

index.test.js :

const sinon = require('sinon');
const proxyquire = require('proxyquire');

describe('64975078', () => {
  it('should pass', () => {
    const cwlStub = {
      filterLogEvents: sinon.stub().returnsThis(),
      promise: sinon.stub().resolves('teresa teng'),
    };
    const awsSdkStub = {
      CloudWatchLogs: sinon.stub().returns(cwlStub),
    };
    const { MyClass } = proxyquire('./', {
      'aws-sdk': awsSdkStub,
    });
    const myClass = new MyClass();
    myClass._getLogs({ 'group-name': 'test group name', 'stream-name': 'test stream name' }, 'test filter');
    sinon.assert.calledOnce(awsSdkStub.CloudWatchLogs);
    sinon.assert.calledWithExactly(cwlStub.filterLogEvents, {
      logGroupName: 'test group name',
      filterPattern: 'test filter',
      logStreamNames: ['test stream name'],
    });
  });
});

unit test result:

  64975078
    ✓ should pass (4719ms)


  1 passing (5s)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.js |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM